2013-05-14 84 views
2

我正在学习C并遇到了结构问题。结构指针数组 - 覆盖struct

假设我有以下结构:

typedef struct { 
    int x; 
} Structure; 

int main (void) { 
    Structure *structs[2]; 
    for(int i = 0; i < 2; i++) { 
    Structure s = {i}; 
    structs[i] = &s; 
    } 
    for(int i = 0; i < 2; i++) { 
    printf("%d\n", structs[i]->x); 
    } 

    return 1; 
} 

输出是:

1 
1 

我不明白为什么新的结构是overring旧的。

这可能是一个愚蠢的问题。但我不明白。

谢谢!

解决:

typedef struct { 
    int x; 
} Structure; 

int main (void) { 
    Structure *structs[2]; 
    for(int i = 0; i < 2; i++) { 
    Structure *s = (Structure *)malloc(sizeof(Structure)); 
    s->x = i; 
    structs[i] = s; 
    } 
    for(int i = 0; i < 2; i++) { 
    printf("%d\n", structs[i]->x); 
    free(structs[i]); 
    } 

    return 1; 
} 

回答

4

对象s不会活过第一for循环的范围。存储它的地址是毫无意义的,并且取消引用它是未定义的行为

+0

谢谢!我知道了!我将我的代码更改为使用堆作为存储。 – user2221323 2013-05-14 18:47:49

3

代码有未定义的行为。您持有本地自动变量的引用。

for(int i = 0; i < 2; i++) { 
    Structure s = {i}; 
    structs[i] = &s; 

} // life time of s ends here 

由于代码有UB,所有投注都关闭。所以,你得到什么输出并不重要。

+0

这不是变量是本地的 - 如果它是静态的,没有UB在这里。正确的(完整)术语是*“本地自动”*变量。 – 2013-05-14 18:40:58

+0

@ H2CO3:实际上,它是*“具有块范围和自动存储时间的对象”*。我不认为这个标准使用术语“本地”来表示这个 - 或者说“变量”。 – 2013-05-14 18:51:12

+0

@KeithThompson对,相当“块范围” - 但我并不暗示“变量”也是术语的一部分(这就是为什么它是引号和斜体的原因)。 – 2013-05-14 18:52:23

1

Structs s = {i};只在你声明它的for循环中有作用域。一旦你离开那个循环,它就不存在了,即使你仍然有一个指向它的指针。之后所有未定义的行为。