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

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -