您的位置:首页 > 编程语言 > C语言/C++

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

2013-11-09 11:00 197 查看

问题:

源代码由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: 1
total_no is: 6
This is seq number 1
u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$


问题解决。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: