首页 > 解决方案 > 为什么这会产生分段错误?

问题描述

我不确定为什么以下会产生分段错误。我已经定义了一个结构,我正在尝试为它存储一个值。

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

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

标签: c

解决方案


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

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

推荐阅读