【问题标题】:C struct problemC结构问题
【发布时间】:2009-11-23 15:27:16
【问题描述】:

我是 C 初学者,我很好奇为什么每次都会出现 Seg Fault:

#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;

但我很好奇为什么使用指针会导致 Seg Fault。

我使用的是 Ubuntu 9.04 (i486-linux-gnu),gcc 版本 4.4.1

【问题讨论】:

    标签: c pointers struct


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 啊,是的,我知道我错过了一件愚蠢的事情......谢谢!
    • 也可以写成:sizeof *test 代替 sizeof(struct Wrapper)。
    【解决方案2】:

    你需要先创建一个 Wrapper 的实例:

    struct Wrapper *test;
    test = new struct Wrapper;
    test->Value = 5;
    

    祝你好运。

    【讨论】:

      【解决方案3】:

      您使用的是未初始化的指针,因此出现了段错误。 如果您打开更多警告,例如使用-Wall,则可能会捕获此类错误

      您需要结合使用 -Wall 和一些优化 (-On) 以显示警告。例如,用

      编译你的代码
      gcc -Wall -O2 -c test.c
      

      导致以下错误消息:

      test.c: Dans la fonction «main» :
      test.c:10: attention : «test» is used uninitialized in this function
      

      虽然使用法语单词,但此编译器消息不是侮辱而是警告;) 请参阅下面的代码为您的测试指针分配内存

      int main () {
        struct Wrapper *test;
        test = malloc(sizeof(struct Wrapper))
        if(test == NULL) {
        /* error handling */
        }
        test->value = 5;
        free(test)
      
        return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-03
        • 2017-06-14
        • 2017-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多