Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with dynamic allocation of memory

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading