ibneko: (Default)
[personal profile] ibneko
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...?

Date: 2006-03-27 07:46 am (UTC)
From: [identity profile] andr00.livejournal.com
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).

Date: 2006-03-27 07:50 am (UTC)
From: [identity profile] andr00.livejournal.com
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.

Date: 2006-03-27 05:21 pm (UTC)
From: [identity profile] ibneko.livejournal.com
Oooh, ok. Thanks.

Expand Cut Tags

No cut tags

Profile

ibneko: (Default)
ibneko

Most Popular Tags

Style Credit

Page generated Jan. 24th, 2026 01:59 pm
Powered by Dreamwidth Studios
January 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 2021