What is the difference between the following declarations?
struct complex *ptr1=(struct complex*)malloc(4*sizeof(struct complex));
struct complex (*ptr1)[4]=(struct complex*)malloc(sizeof(struct complex));
Which is better to use?
What is the difference between the following declarations?
struct complex *ptr1=(struct complex*)malloc(4*sizeof(struct complex));
struct complex (*ptr1)[4]=(struct complex*)malloc(sizeof(struct complex));
Which is better to use?
Let's clean up those calls a bit, first. C does not require you to cast the result of malloc
, and doing so is considered bad practice (C++, on the other hand, does require the cast, but you shouldn't be using malloc
in C++). Also, you can pass the dereferenced target as the operand to sizeof
, so the basic form of any malloc
call looks like
T *p = malloc( sizeof *p * N );
This allocates enough space for N
objects of type T
and assigns the resulting pointer to p
. Each element may be accessed using p[i]
.
So, in the first case, you are doing
struct complex *ptr1 = malloc( sizeof *ptr1 * 4 );
This sets aside space for 4 objects of type struct complex
, each of which is accessed as ptr1[i]
. That's the simpler case.
struct complex (*ptr1)[4] = malloc( sizeof *ptr1 );
This sets aside space for 1 object of type struct complex [4]
(IOW, a 4-element array of struct complex
) and assigns the resulting pointer to ptr1
. Each element would be accessed as either (*ptr1)[i]
or ptr1[0][i]
. You'd really only use this form if you were trying to allocate space for a 2-dimensional array of struct complex
:
struct complex (*p)[4] = malloc( sizeof *p * N );
This allocates space for N
4-element arrays, or more simply an N
x4 array, of struct complex
. Each element would be accessed as p[i][j]
.