-3

What is the difference between the following declarations?

  1. struct complex *ptr1=(struct complex*)malloc(4*sizeof(struct complex));
  2. struct complex (*ptr1)[4]=(struct complex*)malloc(sizeof(struct complex));

Which is better to use?

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
  • 1
    Welcome to Stack Overflow! [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Jul 15 '16 at 10:37
  • 1
    Number 2 is a pointer to an array. It's confusing, difficult to use, and very rarely useful. You'll virtually always want number 1. – Steve Summit Jul 15 '16 at 10:38
  • In the latter you're reserving too little space: for 1 struct complex, not an array of 4 struct complex + all the things said before. – Ilja Everilä Jul 15 '16 at 10:39
  • In first expression we can access using . operator and in second expression we can access using -> operator as, 1. int i;for(i=0;i<3;i++) {ptr1[i].real;ptr1[i].imag} 2. for(i=0;i<3;i++){ptr1[i]->real;ptr[1]->imag}.How this is done in memory. – vikas hurgat Jul 15 '16 at 10:40
  • 1
    the second one , isn't size wrong? – Sourav Ghosh Jul 15 '16 at 10:41
  • Shouldn't a pointer to array of struct be accessed as `(*ptr1)[i].real`, not `ptr1[i]->real`, or is this one of those `a[i]` is `[a]i` things? – Ilja Everilä Jul 15 '16 at 11:09

1 Answers1

0

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 Nx4 array, of struct complex. Each element would be accessed as p[i][j].

John Bode
  • 119,563
  • 19
  • 122
  • 198