C 结构指针数组-重写结构

C 结构指针数组-重写结构,c,arrays,pointers,struct,C,Arrays,Pointers,Struct,我正在学习C,遇到了一个关于结构的问题 假设我有以下结构: 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"

我正在学习C,遇到了一个关于结构的问题

假设我有以下结构:

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;
}
我不明白为什么新结构比旧结构更重要

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

谢谢

已解决:

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;
}
typedef结构{
int x;
}结构;
内部主(空){
结构*structs[2];
对于(int i=0;i<2;i++){
Structure*s=(Structure*)malloc(sizeof(Structure));
s->x=i;
结构[i]=s;
}
对于(int i=0;i<2;i++){
printf(“%d\n”,结构[i]>x);
自由(结构[i]);
}
返回1;
}

对象
s
不会超出第一个
for
循环的范围。存储它的地址是没有意义的,取消引用它是未定义的行为。

代码具有未定义的行为。您持有的是局部自动变量的引用

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

} // life time of s ends here
for(int i=0;i<2;i++){
结构s={i};
结构[i]=&s;
}//s的生命在这里结束

由于代码已被删除,所有赌注均已取消。因此,您得到的输出并不重要。

The
Structs={i}仅在声明它的for循环中具有作用域。一旦您离开该循环,它就不再存在,即使您仍然有指向它的指针。这之后都是未定义的行为。

这不是因为变量是局部变量-如果它是
静态的
,这里就没有UB了。正确(完整)的术语是“本地自动”变量。@H2CO3:实际上,它是“具有块范围和自动存储持续时间的对象”。我不相信这个标准使用“本地”这个术语,也不使用“变量”这个术语。@KeithThompson对,而是“块范围”-但我也没有暗示“变量”是术语的一部分(这就是为什么它排除了引号和斜体)@H2CO3谢谢你纠正我使用正确的术语。@Mahesh为此感谢Keith Thompson-结果我也不是完全正确:)谢谢!我得到了它!我将代码改为使用堆作为存储。
for(int i = 0; i < 2; i++) {
    Structure s = {i};
    structs[i] = &s;

} // life time of s ends here