用strncpy時字符數組和字符指針有著怎樣的區別?#include <iostream>using std::cout;using std::endl;int main(){char ch1[5];char* ch2;char* ch3 = "12345678";strncpy(ch1,ch3,5);//ch1輸出結果:12345&^% (注:后面幾個是亂碼)strncpy(ch3,ch2,5);//ch3輸出結果:12345cout << ch1 <<endl; cout << ch3 <<endl; return 0;}能解釋一下strncpy的運行結果么??int main(){char ch1[5],ch5[5];char ch2[11],ch6[11];char* ch3 = new char[6];char* ch7 = new char[6];char* ch4 = new char[11];char* ch8 = new char[11];char* ch9 = new char[6];char* ch = "12345678";//strcpy(ch1,ch); cout << 1 << ch1 << endl;//strcpy(ch2,ch); cout << 2 << ch2 << endl;//strcpy(ch3,ch); cout << 3 << ch3 << endl;//strcpy(ch4,ch); cout << 4 << ch4 << endl; //上面四行結果均是12345678strncpy(ch5,ch,5); cout << 5 << ch5 << endl; //512345后面亂碼strncpy(ch6,ch,5); cout << 6 << ch6 << endl; //612345后面亂碼strncpy(ch7,ch,5); cout << 7 << ch7 << endl; //712345后亂碼strncpy(ch7,ch,6); cout << 7 << ch7 << endl; //7123456后亂碼strncpy(ch8,ch,5); cout << 8 << ch8 << endl; //812345后面亂碼strncpy(ch9,ch,5); cout << 9 << ch9 << endl; //912345后面亂碼system("pause");return 0;}
2 回答
大話西游666
TA貢獻1817條經驗 獲得超14個贊
操作字串時,不要忘了給最后的'\0'分配空間,不然輸出時就會帶著亂碼,正確的做法是:
char *ch2 = new char[6];
strncpy(ch2, ch3, 5);
ch2[5] = '\0';
cout << ch2 << endl;
不能少了這句
delete[] ch2;
之所以出現亂碼,是因為執行strncpy的過程中并沒有將字串結束符'\0'賦值給目標,目標字串沒有結束符輸出時自然就不知道應該什么時候停止輸出,除非遇到'\0'字符,因此你會看到亂碼,就這樣。
慕的地10843
TA貢獻1785條經驗 獲得超8個贊
分析下strncpy的源代碼應該就明白了 ,庫函數并沒有對dest檢查,有可能dest不是以'\0'結尾, 輸出的時候就會出錯了
char * __cdecl strncpy (
char * dest,
const char * source,
size_t count
)
{
char *start = dest;
while (count && (*dest++ = *source++)) /* copy string */
count--;
if (count) /* pad out with zeroes */
while (--count)
*dest++ = '\0';
return(start);
}
- 2 回答
- 0 關注
- 113 瀏覽
添加回答
舉報
0/150
提交
取消
