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;
}
推荐阅读
- ssh - How to fix path references is ssh?
- python - why locate all on screen in pyautogui returns multiple similar results?
- javascript - How to display escaped HTML inside a code tag generated from markdown sanitized source?
- php - Regex to match four blocks ranges
- javascript - Discord虚荣狙击机器人错误:没有这样的文件或目录
- python - subprocess not working after onefile pyinstaller even with stdout/stdin defined
- java - ORA-02289: 序列不存在 Spring boot
- android - Does ARCore recording & playback degrade accuracy at all?
- javascript - 我怎样才能增加一个数组并让它从第一个索引开始?
- r - 在字段包中的 drape.plot 下绘制 image.plot?