c - 为什么这会产生段错误?

标签 c

我不确定为什么以下内容会产生段错误。我已经定义了一个结构,并且正在尝试向其中存储一个值。

typedef struct {
    int sourceid;
    int destid;
} TEST_STRUCT;

void  main( int argc, char *argv[] )  {
    TEST_STRUCT *test;
    test->sourceid = 5;
}

最佳答案

您声明一个指向该类型的指针。您需要为指向的指针分配内存:

#include <stdlib.h>

typedef struct {
    int sourceid;
    int destid;
} TEST_STRUCT;

int main(int argc, char *argv[])  {
    TEST_STRUCT *test;
    test = malloc(sizeof(TEST_STRUCT));
    if (test) {
        test->sourceid = 5;
        free(test);
    }
    return 0;
}

或者,您可以在堆栈上声明变量:

typedef struct {
    int sourceid;
    int destid;
} TEST_STRUCT;

int main(int argc, char *argv[])  {
    TEST_STRUCT test;
    test.sourceid = 5;
    return 0;
}

关于c - 为什么这会产生段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53789252/

相关文章:

c++ - 如何在android项目中使用NDK?

c - 结构问题,为什么会出现此错误?

c++ - 使用 libcurl 进行 POST 请求

c - "Couldn' 找不到匹配的渲染驱动程序!”来自 SDL_CreateRenderer()?

c - 在C中初始化字符串指针有什么意义

c - fork() 导致为每个进程打印列标题

c - 使用 mmap 映射的内存,并与 mprotect 一起使用

c - 在 C 中检测键盘事件

c++ - 如何从 C 中的字符中减去整数?

memcpy 可以用于类型双关吗?