简体   繁体   中英

Create structure variables in a loop in c

I am trying to create a bunch of struct variables in C. So lets say I have a for loop which runs 3 times and creates three struct variables. My question is that why is it creating the variables that reference the same memory location. Code:

struct arrIndexStruct {
    int *arr;
    int index;
};


int main() {
    int i;
    for (i=0; i<3; i++) {
        struct arrIndexStruct arrayIndexStruct;
        arrayIndexStruct.arr = someArray;
        arrayIndexStruct.index = i;
        printf("%p\n",(void *)&arrayIndexStruct);
    }
}

The output I get is:

0x7ffeed84f690
0x7ffeed84f690
0x7ffeed84f690

Whereas, If I do

struct arrIndexStruct arrayIndexStruct1;
struct arrIndexStruct arrayIndexStruct2;
printf("%p\n",(void *)&arrayIndexStruct1);
printf("%p\n",(void *)&arrayIndexStruct2);

I'll get

0x7ffc484e64d0
0x7ffc484e64e0

What is the difference between the two behaviors and shouldn't for loop have local scope? Thanks!

The variable is only defined since the first appearance in the code and until the end of its enclosing block. When it reaches end of scope, its original memory can be used anything else.

Specifically in the loop the variables always occupy the same location as it's simply the easiest thing compiler can achieve.

The second case is completely different as the first variable remains defined while the second is introduced. You could get the same address in the following example but it depends on compiler and also debug level, optimization, etc.:

{
    struct arrIndexStruct arrayIndexStruct1;
}
{
    struct arrIndexStruct arrayIndexStruct2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM