国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
c語言中字符串比較易錯(cuò)的地方

from http://blog.csdn.net/david_xtd/article/details/14644011

2013.11

問題:

源代碼由C++代碼轉(zhuǎn)化而來,所以對(duì)于C風(fēng)格字符串的比較,仍然使用C++中比較C風(fēng)格字符串的方式

  1. char* pstr = "enable";  
  2. if (pstr == "enable") {  
  3.     PerformTask();  
  4. }  

但在程序運(yùn)行的時(shí)候,發(fā)現(xiàn)PerformTask()始終沒有被調(diào)用到。

解決辦法:

1. 在C++中,問題中所用的字符串比較方式是可行的。

在C中,該種字符串比較方式具有很大的欺騙性和殺傷力,因?yàn)?,程序編譯也能通過,但實(shí)際上所比較的條件總不能成立,所以條件成立后所執(zhí)行的操作總不能完成;

2. 為了防止這類錯(cuò)誤在C語言中出現(xiàn),自己編譯測(cè)試程序的時(shí)候應(yīng)該把Wall選項(xiàng)打開,這樣,編譯的時(shí)候會(huì)有錯(cuò)誤提示;

  1. u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$ gcc -Wall -std=gnu99 -o test_strtok test_strtok.c   
  2. test_strtok.c: In function ‘main’:  
  3. test_strtok.c:49:16: warning: comparison with string literal results in unspecified behavior [-Waddress]  
  4. u1204@u1204-zhw:~/wrk/tmp/cpp_src/c_exer$  
提示應(yīng)該使用正確的字符串處理方式。

3. 示例代碼:

  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. int main() {  
  5.     printf("\n========================================================================\n");  
  6.     char str1[] = "1/6";  
  7.     char* delim1 = "/";  
  8.     char* seq_no = NULL;  
  9.     char* total_no = NULL;  
  10.     seq_no = strtok(str1, delim1);  
  11.     printf("seq_no is: %s\n", seq_no);  
  12.     total_no = strtok(NULL, delim1);  
  13.     printf("total_no is: %s\n", total_no);  
  14.     // if (seq_no == "1") {  
  15.     if (!strcmp(seq_no, "1")) {  
  16.         printf("This is seq number %s\n", seq_no);  
  17.     }  
  18.   
  19.     return 0;  
  20. }  
運(yùn)行結(jié)果:

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


問題解決。




本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
字符串以及內(nèi)存操作相關(guān)函數(shù)
C標(biāo)準(zhǔn)庫函數(shù)淺析
strtok函數(shù)實(shí)現(xiàn)與應(yīng)用
字符串分割
Linux項(xiàng)目實(shí)戰(zhàn)系列之:GPS數(shù)據(jù)解析
字符串分割函數(shù)strtok
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服