简体   繁体   English

C中的字符数组比较

[英]Char array comparison in C

I have following function to compare two char arrays in C: 我有以下函数来比较C中的两个char数组:

short test(char buffer[], char word[], int length) {
    int i;
    for(i = 0; i < length; i++) {
        if(buffer[i] != word[i]) {
            return 0;
        }
    }
    return 1;
}

And somewhere in main: 在主要的某个地方:

char buffer[5]; //which is filled correctly later
...
test(buffer, "WORD", 5);

It returns 0 immediately at i = 0. If I change function to this: 它在i = 0时立即返回0.如果我将函数改为:

short test(char buffer[], int length) {
    int i;
    char word[5] = "WORD";
    for(i = 0; i < length; i++) {
        if(buffer[i] != word[i]) {
            return 0;
        }
    }
    return 1;
}

... it works like a charm. ......它就像一个魅力。 In the first version of function test debugger says that buffer and word arrays are type of char*. 在函数测试的第一个版本中,调试器说缓冲区和字数组是char *的类型。 In the second version of function test it says that the buffer is type of char* and the test array is type of char[]. 在函数测试的第二个版本中,它表示缓冲区是char *类型,测试数组是char []类型。 Function strcmp() does not work neither. 函数strcmp()也不起作用。

What is actually wrong here? 这里究竟出了什么问题? Program is made for PIC microcontroller, compiler is C18 and IDE is MPLAB. 程序用于PIC单片机,编译器为C18,IDE为MPLAB。

Hmm... 嗯...

Sometimes in embedded systems there is difference where strings are stored. 有时在嵌入式系统中存储字符串的区别。

In the first example you define a string which is stored in flash code region only. 在第一个示例中,您定义了一个仅存储在闪存代码区域中的字符串。 So the comparison will fail with index 0 because of the memory area difference. 因此,由于存储区域的差异,比较将因索引0而失败。

The second example you define a local variable which contain the same string. 第二个示例定义包含相同字符串的局部变量。 This will be located in RAM, so the comparison works since they are both in RAM. 这将位于RAM中,因此比较起作用,因为它们都在RAM中。

I would test following: 我会测试以下内容:

char buffer[5]; //which is filled correctly later
char word[5] = "WORD";
...
test(buffer, word, 5);

Most likely it is going to work because the comparison is done in RAM totally. 很可能它会起作用,因为比较完全在RAM中完成。

Yes and remove the \\0 since the "WORD" will null terminate automatically. 是,并删除\\ 0,因为“WORD”将自动终止。

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

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