C结构问题

标签 c pointers struct

我是一个 C 初学者,我很好奇为什么这每次都会给我一个段错误:

#include <stdio.h>
#include <stdlib.h>

struct Wrapper {
  int value;
};

int main () {
  struct Wrapper *test;
  test->value = 5;

  return 0;
}

我知道我还没有完全理解指针,但我认为

struct_ptr->field 

相同
(*struct_ptr).field

所以尝试在该领域进行分配应该没问题。这按预期工作:

struct Wrapper test;
test.value = 5;

但我很好奇为什么使用指针会导致段错误。

我在 Ubuntu 9.04 (i486-linux-gnu),gcc 版本 4.4.1

最佳答案

您没有将指针分配给任何东西。它是指向谁知道什么的未初始化指针,因此结果未定义。

您可以将指针分配给动态创建的实例,如下所示:

int main () {
  struct Wrapper *test;
  test = (struct Wrapper *) malloc(sizeof(struct Wrapper));
  test->value = 5;
  free(test);

  return 0;
}

编辑:意识到这是 C,而不是 C++。相应地修复了代码示例。

关于C结构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1783844/

相关文章:

c# - 结构与类

c - C 结构中的静态变量

检查命令是否在 Makefile 中不返回任何内容

c - 从屏幕空间读取顶点颜色

c - 不兼容的指针不允许将 csv 放置到二维数组中

c++ - Direct3D typedef 用法

c - 如何在 Visual Studio 2010 for C 中使用 igraph(和其他库)?

c - 为什么不能使用 malloc 在 C 中调整数组大小?

C 不为新的 char 数组分配内存

c# - 如何以编程方式检查类型是结构还是类?