在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/C++/ C++ strcpy()的用法

C++ strcpy()的用法

#include <iostream>
int main()
{
    using namespace std;
    char a[3];
    strcpy(a,"affd sfasdfsdf");
    cout << a[5] << endl;
    cout << a << endl;
}

這里的輸出結(jié)果居然是:
s
affd sfasdfsdf
奇怪,a的長度明明是3,為什么會有這樣的輸出結(jié)果呢?

回答
編輯回答
遺莣

strcpy()是C標(biāo)準(zhǔn)函數(shù)。
該函數(shù)不會檢查數(shù)組越界的情況?。?!

2017年4月16日 01:29
編輯回答
離夢

關(guān)于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.

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

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

2017年9月27日 17:23
編輯回答
挽青絲

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

2018年2月20日 15:09