简体   繁体   English

strcmp在“相同”字符串上不返回0

[英]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. 因此,代码将初始字符存储在有界数组(9是任何输入的最大大小)的文本文件中,然后如果实际大小较小,则移动到实际输入大小的数组中。 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? 例如,如果输入为“ initiate”,则将charstruction []初始化为大小8。这很好,因为我通过打印数组的元素对其进行了测试,但是数组与“ initiate”之间的strcmp却没有返回0。为什么呢?

input is "initiate", for example, then char instruction[] is initialized to size 8 输入是“初始化”,例如,然后将char指令[]初始化为大小8

You can't pass that to strcmp because strcmp expects null terminated string. 您不能将其传递给strcmp因为strcmp需要以null结尾的字符串。 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. 由于字符串“ initiate”中有8个字符,因此存储它的数组必须至少具有9号,以便为空终止符留出空间-应在最后一个字符之后。

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

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