gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Quick sizeof question, bit confused

#149008 - Rajveer - Sun Jan 13, 2008 3:13 pm

I have a struct

Code:
struct ObjModelCollision
{
   //blahblah;
   u16* TimestampArray;
   //blahblah;
};
struct ObjModelCollision* ModelColl = malloc(sizeof(struct ObjModelCollision));


The pointer TimestampArray will point to an array of u16 of size SizeOfArray. When creating the array that TimestampArray points to, instead of doing

Code:
ModelColl->TimestampArray = malloc(sizeof(u16)*SizeOfArray);


I want to replace u16 with the type of TimestampArray, so would I do

Code:
ModelColl->TimestampArray = malloc(sizeof(ModelColl->TimestampArray)*SizeOfArray);


even though TimestampArray is a pointer?

#149014 - Cearn - Sun Jan 13, 2008 4:39 pm

Probably not. sizeof(ModelColl->TimestampArray) gets the size of the pointer, which is 4. If you want the type of an array element (u16 in this case), try sizeof(ModelColl->TimestampArray[0]).

#149015 - Rajveer - Sun Jan 13, 2008 5:00 pm

Even though at the time of calling sizeof, there is no TimestampArray[0]? This website says I should do

Code:
malloc(sizeof(*ModelColl->TimestampArray)*SizeOfArray);

(with the extra star) which doesn't make sense to me either, as it's a pointer to a pointer...

#149017 - nipil - Sun Jan 13, 2008 5:16 pm

*ModelColl->TimestampArray is the same as ModelColl->TimestampArray[0].

Lets shorten and say you delared T p[123], then *p and p[0].
Both return the value of the first element of the possible list, with its associated type T.
So, sizeof(*p) and sizeof(p[0]) both return the same value, ie sizeof(T).

Only thing is, in both cases, as you're using indirection to get an element from a pointer,
"p" has to point to an allocated object. Not necessarily an array, but at least one element,
or AFAIK you'll get a segfault.

#149022 - Rajveer - Sun Jan 13, 2008 5:53 pm

Oops oh yeah, so since you're dereferencing *ModelColl->TimestampArray, sizeof takes its dereferenced type (so the type of ModelColl-TimestampArray[0]).

Hmm I tend to forget pointer basics quite frequently. Cheers guys!