I'm learning C and encountered a problem with structs.
Let's assume I have the following struct:
typedef struct {
int x;
} Structure;
int main (void) {
Structure *structs[2];
for(int i = 0; i < 2; i++) {
Structure s = {i};
structs[i] = &s;
}
for(int i = 0; i < 2; i++) {
printf("%d\n", structs[i]->x);
}
return 1;
}
The output is:
1
1
I don't understand why the new struct is overring the old one.
It might be a stupid problem. But I don't get it.
Thanks!
Solved:
typedef struct {
int x;
} Structure;
int main (void) {
Structure *structs[2];
for(int i = 0; i < 2; i++) {
Structure *s = (Structure *)malloc(sizeof(Structure));
s->x = i;
structs[i] = s;
}
for(int i = 0; i < 2; i++) {
printf("%d\n", structs[i]->x);
free(structs[i]);
}
return 1;
}