'Segmentation fault (core dumped)' 尝试更改数组值时出错
'Segmentation fault (core dumped)' error when trying to alter an array's values
我的程序是一个交互式计算器,用户可以在其中输入类似 'add 2 5' 的内容,它会运行 add()
函数,返回“5”。
我的程序的工作方式是它使用 strtok()
将用户的输入分解为标记:第一个标记决定程序做什么(即加、除等),接下来的两个是函数中使用的值。
我遇到的问题是我的 while 循环试图将第二个和第三个标记(值)放入整数数组中:
char input[MAX];
char *token;
int values[2];
int counter = 0;
fgets(input, MAX, stdin);
token = strtok(input, " ");
while (token != NULL) {
token = strtok(NULL, " ");
values[counter] = atoi(token);
counter++;
}
Segmentation fault (core dumped)
程序应该如何解释信息的示例:
if (strcmp(token, "add") == 0) {
answer = add(values[0], values[1]);
}
add()
函数的示例:
int add(int x, int y) {
int z = x + y;
return z;
}
我做错了什么吗?
在 token
更新后,您必须检查 token
是否 NULL
。
此外,您还需要保存指向第一个标记(命令)的指针以便稍后对其进行解释。
char input[MAX];
char *token;
char *command; /* add this */
int values[2];
int counter = 0;
fgets(input, MAX, stdin);
token = strtok(input, " ");
command = token; /* add this */
while (token != NULL) {
token = strtok(NULL, " ");
if (token == NULL) break; /* add this */
values[counter] = atoi(token);
counter++;
}
然后,使用保存的指针进行解释。
if (strcmp(command, "add") == 0) { /* use command, not token */
answer = add(values[0], values[1]);
}
我的程序是一个交互式计算器,用户可以在其中输入类似 'add 2 5' 的内容,它会运行 add()
函数,返回“5”。
我的程序的工作方式是它使用 strtok()
将用户的输入分解为标记:第一个标记决定程序做什么(即加、除等),接下来的两个是函数中使用的值。
我遇到的问题是我的 while 循环试图将第二个和第三个标记(值)放入整数数组中:
char input[MAX];
char *token;
int values[2];
int counter = 0;
fgets(input, MAX, stdin);
token = strtok(input, " ");
while (token != NULL) {
token = strtok(NULL, " ");
values[counter] = atoi(token);
counter++;
}
Segmentation fault (core dumped)
程序应该如何解释信息的示例:
if (strcmp(token, "add") == 0) {
answer = add(values[0], values[1]);
}
add()
函数的示例:
int add(int x, int y) {
int z = x + y;
return z;
}
我做错了什么吗?
在 token
更新后,您必须检查 token
是否 NULL
。
此外,您还需要保存指向第一个标记(命令)的指针以便稍后对其进行解释。
char input[MAX];
char *token;
char *command; /* add this */
int values[2];
int counter = 0;
fgets(input, MAX, stdin);
token = strtok(input, " ");
command = token; /* add this */
while (token != NULL) {
token = strtok(NULL, " ");
if (token == NULL) break; /* add this */
values[counter] = atoi(token);
counter++;
}
然后,使用保存的指针进行解释。
if (strcmp(command, "add") == 0) { /* use command, not token */
answer = add(values[0], values[1]);
}