我在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
设置为任何值,因此它可能指向任何地方! - 即您正在调用未定义的行为。
快速修复:
Position instance;
position = &instance;
关于C 编程,将结构体中的 int 成员分配给整数时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36497514/