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