亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C++ strcpy()的用法

C++ strcpy()的用法

C++
幕布斯6054654 2018-09-06 17:34:14
#include <iostream>int main(){    using namespace std;    char a[3];    strcpy(a,"affd sfasdfsdf");    cout << a[5] << endl;    cout << a << endl; }這里的輸出結果居然是:saffd sfasdfsdf奇怪,a的長度明明是3,為什么會有這樣的輸出結果呢?
查看完整描述

2 回答

?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

關于char *strcpy( char *dest, const char *src );,去看一下cppreference里的描述:

Copies the null-terminated byte string pointed to by src, including
the null terminator, to the character array whose first element is
pointed to by dest. The behavior is undefined if the dest array is
not large enough. The behavior is undefined if the strings overlap.
The behavior is undefined if either dest is not a pointer to a
character array or src is not a pointer to a null-terminated byte
string.

重點是The behavior is undefined if the dest array is not large enough,意思說如果你的a沒有足夠的空間放下你的字符串字面量,編譯器可以隨心所欲的給出任何結果,也不需要給出任何的報錯(當然編譯器也可以給出貌似正確的結果就像你給出的stdout那樣)。

另外,個人的觀點是能用std::string的時候(不需要考慮兼容),就盡量不要用char *,費心費力還容易寫錯。


查看完整回答
反對 回復 2018-09-08
?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

這個已經超出了a的長度,在vs中能輸出,但提示變量a已經被破壞,正常a應該存放兩個字符,末尾以\0結束。如果能正常輸出,且不提示錯誤的話,和具體的編譯器有關,比如vc的顯示結果后會延遲1秒,dev-c++則沒有。

查看完整回答
反對 回復 2018-09-08
  • 2 回答
  • 0 關注
  • 1168 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號