Re:C Craft
by jgrahamc on Friday December 18, 2009 @10:58AM
(#1003298)
I noticed that too, and what's weird is that's not at all how you should do it. Since the char c[0] has zero size you can do sizeof on the struct so that you can do the malloc correctly.
And if your compiler won't let you do char c[0] you can do char c[1] and either blow a byte, or do the calculation correctly. Note that you have to be careful with this sort of allocation if you are on a machine that has certain alignment requirements (e.g. Sun).
[ Parent
| on HN ]
Well, being pedantic, that should be
struct thing *foo = malloc(sizeof(struct thing) + sizeof(char) * i_need);
since sizeof(char) isn't guaranteed to be 1 byte on all systems.Actually, the C standard guarantees that char is equal to one byte.