I acknowledge that all three of these have a different meaning. But, I don't understand on what particular instances would each of these apply. Can anyone share an example for each of these? Thank you.
malloc(sizeof(int))
malloc(sizeof(int *))
(int *)malloc(sizeof(int))
malloc(sizeof(int))
means you are allocating space off the heap to store anint
. You are reserving as many bytes as anint
requires.This returns a value you should cast toAs some have noted, typical practice in C is to let implicit casting take care of this.int *
. (A pointer to anint
.)malloc(sizeof(int*))
means you are allocating space off the heap to store a pointer to anint
. You are reserving as many bytes as a pointer requires. This returns a value you should cast to anint **
. (A pointer to a pointer to anint
.)(int *)malloc(sizeof(int))
is exactly the same as the first call, but with the the result explicitly casted to a pointer to anint
.Note that on many architectures, an
int
is the same size as a pointer, so these will seem (incorrectly) to be all the same thing. In other words, you can accidentally do the wrong thing and have the resulting code still work.The syntax pattern that is most foolproof is:
This syntax will not force you to change the code if the type (and or size...) of *p changes, eg in
Which will avoid problems like
, plus: the
sizeof expr
form is also shorter.UPDATE: to demonstrate the correctness of
p = malloc(CNT * sizeof *p)
this test program:Which outputs here: