【发布时间】:2016-04-08 10:37:58
【问题描述】:
我在 Linux 环境中使用 ansi C 编程,我正在使用 gcc 编译器。 我有以下代码
#define USER_IN_LEN 15
#define EXTRA_SPACES 2
#define DELIMS " ,\n"
//define the sruct
typedef struct position
{
int x;
int y;
} Position;
char choice[USER_IN_LEN + EXTRA_SPACES];
//define pointers for strtok and strtol
char *tok;
char *end;
//create pointer o type Position
Position *position;
//get user input with fgets
fgets(choice, USER_IN_LEN, stdin);
//tokenize
tok = strtok(choice, DELIMS);
tok = strtok(NULL, DELIMS);
position->x = (int)strtol(tok, &end, 0); //error, segmentation fault
tok = strtok(NULL, DELIMS);
position->y = (int)strtol(tok, &end, 0);//error, segmentation fault
基本上,该程序获取用户输入的一些值并将它们存储在位置结构中,我在网上做了一些研究,发现我可以使用这个 position->y = int ,但为什么它不能在这里与 strtol 一起使用?我运行了调试器,但没有多大帮助
【问题讨论】:
-
Position *position是一个未初始化的指针。如果你想取消引用它,你必须让它指向某个有效的地方,可能是通过mallocing 内存。
标签: c gcc struct segmentation-fault strtol