gpt4 book ai didi

c - strcmp 不会在 'identical' 字符串上返回 0

转载 作者:行者123 更新时间:2023-11-30 18:53:00 25 4
gpt4 key购买 nike

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

因此,代码将文本文件中的初始字符存储在有界数组中(9 是任何输入的最大大小),然后移动到实际输入大小的数组(如果它恰好更小) 。例如,如果输入是“initiate”,则 char instructions[] 被初始化为大小 8。这工作正常,因为我通过打印数组的元素来测试它,但数组和“initiate”之间的 strcmp 却不起作用返回 0。这是为什么?

最佳答案

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

您无法将其传递给 strcmp,因为 strcmp 需要以 null 结尾的字符串。由于字符串“initiate”中有 8 个字符,因此存储它的数组的大小必须至少为 9,以便为空终止符留出空间 - 它应该位于最后一个字符之后。

关于c - strcmp 不会在 'identical' 字符串上返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33814847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com