What am I missing? I'm a beginner in C, but still the result I get is unexpected for me. I simplified the case to get only the error.
struct str {
int a;
};
struct str* strArray[100];
int main() {
for (int i = 0; i < 100; i++) {
struct str str1;
str1.a=i;
strArray[i]=&str1;
}
for(int i = 0; i < 100; i++) {
printf("i:\t%d\n",strArray[i]->a);
}
return 0;
}
The result printed is a hundred 99s. What I would expect is: 1, 2, 3 ...
2 Answers 2
This declaration inside the loop
struct str str1;
produces a variable of type struct str that is valid only for the duration of the iteration of the loop in which it has been created. Once the iteration is over, str1 becomes invalid. If you decide to access it by pointer outside the scope of that iteration, you get undefined behavior.
You can use malloc to make "durable" structs for use later in the program:
strArray[i]= malloc(sizeof(struct str));
strArray[i]->a = i;
Since your structs are allocated dynamically, you need to free them once you are done using strArray elements:
for(int i = 0; i < 100; i++) {
free(strArray[i]);
}
Comments
Whole strArray is pointing to str1 which contains 99 at last so your whole array locations pointing to 99 which str1 contains at last of first loop iteration.
1 Comment
str1.a is undefined after the first loop completes (in fact, after each iteration of that loop completes) ... it need not be 99.
struct str, namelystr1.strArrayonly contains pointers, and they all point tostr1. In fact, your program has undefined behavior because you're accessingstr1outside its scope, so the program could print anything at all (or nothing).