Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc with int **

if I have as an argument int **a in my function I was wondering what is the difference between a = (int **)malloc(sizeof(a)*(length) and *a = (int *)malloc(sizeof(a)*(length) I've discovered malloc last week so I don't understand everything yet. Thank you !

like image 965
Patrick Resal Avatar asked Jul 09 '26 21:07

Patrick Resal


2 Answers

malloc just returns a void * pointer, nothing more.

a is a pointer to pointer.

The right side of the Equals Sign is not important here, so leave the right side alone. Now we got:

// 1st code fragment
int **a1;
// Asign a null pointer to a1, now a1 is a NULL pointer
a1 = (int **)NULL;

// 2rd code fragment
int **a2;
// Asign a null pointer to the pointer pointed by a2.
// Here may crash actually, because a2 is not initialized yet.
*a2 = (int *)NULL;
like image 143
Galaxy Avatar answered Jul 11 '26 12:07

Galaxy


The first case takes the address of the memory allocated by the call to malloc, and assigns it to your variable a. The second takes the address of the memory allocated by malloc and stores that in whatever memory a happens to be pointing at.

There's another question here, though, which is specifying how much memory you should allocate. If you want a to store an array of pointers to integers, I would use expression a = (int**) malloc( length * sizeof(*a) ); which makes it clear that you are allocating space for a number of integer pointers.

On the other hand, if you want to allocate space for a number of integers (not pointers) and you are sure that a is pointing at a variable of type int*, then use the expression *a = (int*) malloc( length * sizeof *(*a) );

Finally, note that (per chux's link below) it is unnecessary and not recommended to cast the result of malloc(). I have left in the casts here only for clarity, because they illustrate that we're storing the returned value in a different type of variable in each case.

like image 41
Tim Randall Avatar answered Jul 11 '26 13:07

Tim Randall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!