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 ?
CodePudding user response:
In the first code snippet, this statement is wrong:
p=malloc(n*sizeof(int));
because the type of p
is int **
, so, p
can be pointer to a int *
type. It should be:
p = malloc (n * sizeof (int *));
^^^^^
In the second code snippet, allocation to p
is correct because of this - sizeof*p
. The type of *p
is int *
. So, sizeof*p
is equivalent to sizeof (int *)
.
But in second code snippet, this is wrong:
p[i]=malloc(n*sizeof*p);
because the type of p[i]
is int *
i.e. pointer to an int
. So, it can point to an integer. Hence, you should allocate memory of n * sizeof (int)
. It should be
p[i] = malloc (n * sizeof *p[i]);
Here, n * sizeof *p[i]
is equivalent to n * sizeof (int)
because the type of *p[i]
is int
.
Its matter of choice to use whichever style you want to. The matter of fact is that, you should have a good understanding of what you are doing and how it works because the lack of understanding can result in mistake in any style that you choose (as you can see there is mistake in both the code snippets you have shown).
CodePudding user response:
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