简体   繁体   English

在 c 中的循环中创建结构变量

[英]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.我正在尝试在 C 中创建一堆结构变量。所以假设我有一个运行 3 次并创建三个结构变量的 for 循环。 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?这两种行为之间有什么区别,并且 for 循环不应该具有局部作用域? 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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