c - Array of struct pointers - overrides struct -
i'm learning c , encountered problem structs.
let's assume have following struct:
typedef struct { int x; } structure; int main (void) { structure *structs[2]; for(int = 0; < 2; i++) { structure s = {i}; structs[i] = &s; } for(int = 0; < 2; i++) { printf("%d\n", structs[i]->x); } return 1; }
the output is:
1 1
i don't understand why new struct overring old one.
it might stupid problem. don't it.
thanks!
solved:
typedef struct { int x; } structure; int main (void) { structure *structs[2]; for(int = 0; < 2; i++) { structure *s = (structure *)malloc(sizeof(structure)); s->x = i; structs[i] = s; } for(int = 0; < 2; i++) { printf("%d\n", structs[i]->x); free(structs[i]); } return 1; }
the object s
doesn't live beyond scope of first for
loop. storing address pointless, , dereferencing undefined behaviour.
Comments
Post a Comment