c语言中字符串比较易错的地方

来源:互联网 发布:方文山黄伟文 知乎 编辑:程序博客网 时间:2024/06/05 00:39

问题:

源代码由C++代码转化而来,所以对于C风格字符串的比较,仍然使用C++中比较C风格字符串的方式

char* pstr = "enable";if (pstr == "enable") {    PerformTask();}

但在程序运行的时候,发现PerformTask()始终没有被调用到。

解决办法:

1. 在C++中,问题中所用的字符串比较方式是可行的。

在C中,该种字符串比较方式具有很大的欺骗性和杀伤力,因为,程序编译也能通过,但实际上所比较的条件总不能成立,所以条件成立后所执行的操作总不能完成;

2. 为了防止这类错误在C语言中出现,自己编译测试程序的时候应该把Wall选项打开,这样,编译的时候会有错误提示;

u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$ gcc -Wall -std=gnu99 -o test_strtok test_strtok.c test_strtok.c: In function ‘main’:test_strtok.c:49:16: warning: comparison with string literal results in unspecified behavior [-Waddress]u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$
提示应该使用正确的字符串处理方式。

3. 示例代码:

#include <stdio.h>#include <string.h>int main() {    printf("\n========================================================================\n");    char str1[] = "1/6";    char* delim1 = "/";    char* seq_no = NULL;    char* total_no = NULL;    seq_no = strtok(str1, delim1);    printf("seq_no is: %s\n", seq_no);    total_no = strtok(NULL, delim1);    printf("total_no is: %s\n", total_no);    // if (seq_no == "1") {    if (!strcmp(seq_no, "1")) {        printf("This is seq number %s\n", seq_no);    }    return 0;}
运行结果:

u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$ ./test_strtok ========================================================================seq_no is: 1total_no is: 6This is seq number 1u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$


问题解决。




原创粉丝点击