简体   繁体   中英

strcmp doesn't return 0 on 'identical' strings

char c;
char unprocessed_instruction[9];
int i;

for (i=0; i<num_tasks; i++){
    c = fgetc(fp);
    int j = 0;
    while (c != ' '){
        unprocessed_instruction[j]  = c;
        j = j + 1;
        c = fgetc(fp);
    }
    char instruction[j];
    for (int i=0; i<j; i++){
        instruction[i] = unprocessed_instruction[i];
    }
    for (int i=0; i<j; i++){
        printf("%c\n", instruction[i]);
    }
    int i = strcmp(instruction, "initiate");
    printf("%i\n", i);
}

So the code stores the initial characters in a text file in an bounded array (9 is the max size of any input), and then moves into an array that is the size of the actual input, if it happens to be smaller. If the input is "initiate", for example, then char instruction[] is initialized to size 8. This works fine, as I test it with printing the elements of the array, but a strcmp between the array and "initiate" does not return 0. Why is that?

input is "initiate", for example, then char instruction[] is initialized to size 8

You can't pass that to strcmp because strcmp expects null terminated string. Since there are 8 characters in string "initiate", the array which stores it must at least have size 9, to allow for space for the null terminator - which should follow the last character.

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