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 ...
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).