[英]'Segmentation fault (core dumped)' error when trying to alter an array's values
My program is an interactive calculator, where the user may enter something like 'add 2 5' and it runs the add()
function, returning '5'.我的程序是一个交互式计算器,用户可以在其中输入“add 2 5”之类的内容,然后运行add()
function,返回“5”。
The way my program works is that it uses strtok()
to break the user's input into tokens: the first token determines what the program does (ie adds, divides, etc), and the next two are the values used in the function.我的程序的工作方式是它使用strtok()
将用户的输入分解为标记:第一个标记确定程序做什么(即加法、除法等),接下来的两个是 function 中使用的值。
The problem I am having is with my while loop that tries to put the 2nd and 3rd tokens (the values) into an array of integers:我遇到的问题是我的 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)分段错误(核心转储)
An example of how the program is supposed to interpret the information:程序应该如何解释信息的示例:
if (strcmp(token, "add") == 0) {
answer = add(values[0], values[1]);
}
An example of the add()
function: add()
function 的示例:
int add(int x, int y) {
int z = x + y;
return z;
}
Is there something I am doing wrong?有什么我做错了吗?
You must check if token
is NULL
after token
is updated.更新token
后,您必须检查token
是否为NULL
。 Also, you will want to save the pointer to the first token (command) to interpret it later.此外,您还需要保存指向第一个标记(命令)的指针,以便稍后对其进行解释。
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++;
}
Then, use the saved pointer to interpret.然后,使用保存的指针进行解释。
if (strcmp(command, "add") == 0) { /* use command, not token */
answer = add(values[0], values[1]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.