簡體   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