Until now I did allocate the memory for a matrix like this :
int **p,n;
scanf("%d",&n);
p=malloc(n*sizeof(int));
for(int i=0;i<n;i++)
p[i]=malloc(n*sizeof(int));
- but someone told me to do like this :
int **p,n;
scanf("%d",&n);
p=malloc(n*sizeof*p);
for(int i=0;i<n;i++)
p[i]=malloc(n*sizeof*p);
sizeof(p) is not 0 because is not allocated ??
Which one is good ?
>Solution :
First of all, p=malloc(n*sizeof(int)); is wrong – you aren’t allocating a 2D array but an array of pointers, each pointing to an array of int. This needs to be p=malloc(n*sizeof(int*)); for the first example to be correct.
Apart from that bug, this is a matter of subjective coding style. Some prefer to write malloc(n*sizeof*p); since sizeof *p gives the size of the pointed-at item. This works because sizeof isn’t evaluated for side effects, so no pointer de-referencing actually happens. The size is computed at compile-time.
A third style is also possible: p=malloc( sizeof(int*[n]) );. Here you make it more explicit that you are declaring an array. Which of these three styles to use is subjective and mostly a matter of opinion.
And in case you want to allocate actual 2D arrays allocated adjacently, you need to do as advised here instead: Correctly allocating multi-dimensional arrays