繁体   English   中英

尝试更改数组的值时出现“分段错误(核心转储)”错误

[英]'Segmentation fault (core dumped)' error when trying to alter an array's values

我的程序是一个交互式计算器,用户可以在其中输入“add 2 5”之类的内容,然后运行add() function,返回“5”。

我的程序的工作方式是它使用strtok()将用户的输入分解为标记:第一个标记确定程序做什么(即加法、除法等),接下来的两个是 function 中使用的值。

我遇到的问题是我的 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++;
}

分段错误(核心转储)

程序应该如何解释信息的示例:

if (strcmp(token, "add") == 0) {
    answer = add(values[0], values[1]);
}

add() function 的示例:

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]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM