?

Log in

No account? Create an account
IBNeko's Journal-Nyo~!
ibneko
ibneko
C malloc/pointer question
What's the difference between:

image_cover_t* new_cover; /* the new cover *
/* Allocate the new image cover. */
if (NULL == (new_cover = malloc (sizeof (*new_cover)))) {...


and


int *iptr;
iptr = (int *)malloc(10 * sizeof(int));
if (iptr == NULL){...


Namely, the malloc line... I don't understand why one uses sizeof(address-of-variable) and another uses sizeof(variable-type)? Help?

(Yeah, this is probably absurdly basic, but.. I dunno. This is what I get for learning Java before C, and not really fully understanding memory)

Like.. would, "if (NULL == (new_cover = malloc (sizeof (image_cover_t)))) {..." work too...?
3 happy kittens | Leave catnip
Comments
andr00 From: andr00 Date: March 27th, 2006 07:46 am (UTC) (Link)
sizeof() will return the size of whatever type the expression you give it evaluates to. sizeof(int) returns the size of an int type variable.
int hi_I_am_an_int_type_variable;
[...]
sizeof(hi_I_am_an_int_type_variable)
returns the same thing.

*new_cover in that first sizeof() is a dereferenced pointer to a type (that's what the * does in this usage, which I consider a confusing part of C), so it is really sizeof(image_cover_t).
andr00 From: andr00 Date: March 27th, 2006 07:50 am (UTC) (Link)
Oh yeah, but the reason they might not want to just put sizeof(image_cover_t) is that if in the future someone changes the part where new_cover gets declared so that it's something else (like a * to fancier_image_cover_t), they won't have to also change the malloc part. Cuts down on touch points.
ibneko From: ibneko Date: March 27th, 2006 05:21 pm (UTC) (Link)
Oooh, ok. Thanks.
3 happy kittens | Leave catnip