4 ms·
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 c
by jgrahamc 17y ago
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.
struct thing {
int n;
char c[0];
};
int i_need = 16;
struct thing * foo = malloc(sizeof(struct thing)+i_need);
foo->n = i_need;
for (int i = 0; i < foo->n; i++ ) {
foo->c[i] = 'a' + i;
}
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).
- cpr 17y agoWell, 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.