[問題] bsearch() 的錯誤

看板C_and_CPP作者 (龍騎士2)時間14年前 (2010/04/15 01:44), 編輯推噓2(201)
留言3則, 3人參與, 最新討論串1/1
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 ) ( 未必需要依照此格式,文章條理清楚即可 ) 遇到的問題: (題意請描述清楚) 我使用bsearch來搜尋已經定義的多個字串, 但搜尋這些字串的其中一個, 卻無法得到正確的回應 希望得到的正確結果: 當輸入的字串, 屬於這些字串的其中一個時, 可以正確得到回應 程式跑出來的錯誤結果: 以下是我執行 bsearch 前給予 bsearch 的參數, 在執行前先輸出來看 s=shutdown command[0]=init command[1]=shutdown command[2]=set command[3]=exit command[4]=ls numcommands=5 sizeof command[0]=4 s1=shutdown, s2=set s1=shutdown, s2=ls t=0 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) Linux, CodeBlocks, C++ 有問題的code: (請善用置底文標色功能) int cmpstr(const void *vs1, const void *vs2){ char * const *s1 = (char* const*)vs1; char * const *s2 = (char* const*)vs2; cout<<"s1="<<*s1<<", s2="<<*s2<<endl; return strcmp(*s1, *s2); }; 以下是某副程式片段 ---------------------------------------- char *command[] = { "init", "shutdown", "set", "exit", "ls" }; //先把輸入資料列印出來看 cout<<"\ns="<<s<<endl; for (unsigned int i=0;i<numcommands;i++) cout<<"command["<<i<<"]="<<command[i]<<endl; cout<<"numcommands="<<numcommands<<endl; cout<<"sizeof command[0]=" << (sizeof command[0]) <<endl; t = bsearch(&s, command, numcommands, sizeof command[0], cmpstr); 補充說明: -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.115.34.47

04/15 01:59, , 1F
bsearch只能對排序好的陣列做搜尋吧..?
04/15 01:59, 1F

04/15 12:36, , 2F
這故事告訴我們使用前要先看說明書..
04/15 12:36, 2F

04/15 21:08, , 3F
喔... 謝謝
04/15 21:08, 3F
文章代碼(AID): #1BnVxe9d (C_and_CPP)