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$
问题解决。
相关文章推荐
- C语言字符串大小比较
- C语言 编写程序实现字符串比较,不允许使用strcmp函数。
- C语言——比较字符串的大小及字符串的合并
- LR中用C语言比较两个字符串变量
- (c语言)比较两个字符串的长度
- C语言字符串输入函数的比较与解析
- LoadRunner/C语言 实现字符串数组比较
- 在C语言中比较两字符串(自定义函数)
- 字符串比较忽略大小写 c语言实现
- [string]C语言中字符串使用需注意的地方
- iOS中C语言的字符串比较
- C语言字符和字符串的比较
- strcmp 字符串比较,c语言实现
- (c语言)比较三个字符串的大小
- C语言strcmp()函数:比较字符串(区分大小写)
- gets与scanf_C语言中两种字符串输入方法比较
- C语言字符串比较(转)
- C语言的字符串比较与汇编的对照
- C语言strcmp()函数:比较字符串(区分大小写)
- c语言中指针数组易错的一个地方