简体   繁体   中英

'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'.

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.

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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