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).