The scope of bar
only exists within one iteration of the loop. That means that when the next struct foo
is created, it will be put in the same place as the old bar
, because as far as the compiler sees it, the bar
is no longer necessary. Looking at your example, it doesn't seem like you need to handle all of the bar
's at once. So you might be okay with them all being at the same location. However, if you need to deal with multiple at a time, I can think of two possible solutions.
Putting the scope outside of the loop
To do this, you'll need an array of struct foo
's. The scope of the array needs to be outside of the loop. For example:
struct foo bar_list[5];
for (i = 2; i < 7; i++) {
printf("struct %p\n", (void *)&bar_list[i - 2]);
// use the foo's here
}
Then each iteration of your for loop can modify one of the values
Allocating on the heap
If you're okay with storing five pointers in memory, you can allocate each bar somewhere on the heap. You would probably end up just using an array anyway, so this would probably only be useful if you needed to return the structs into another function. You'd need to do something like this:
struct foo* bar_list[5];
for (i = 2; i < 7; i++) {
bar_list[i - 2] = malloc(sizeof(struct foo));
printf("struct %p\n", (void *)bar_list[i - 2]);
// do anything else you need to do
}
It's also worth mentioning, as someone else pointed out, that %p
would be used to print a pointer address.