The usage of CPP strcpy ()

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

the output here is:
s
affd sfasdfsdf
strange, the length of an is obviously 3, why is there such an output?

CPP
Apr.30,2021

for char * strcpy (char * dest, const char * src); , take a look at the description in 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 point is The behavior is undefined if the dest array is not large enough , which means that if your a does not have enough space to put down your string literals, the compiler can give any results at will without giving any errors (of course, the compiler can also give seemingly correct results like your stdout ).

in addition, my personal view is that when std::string can be used (without considering compatibility), try not to use char * , which is easy to make mistakes.


this has exceeded the length of an and can be output in vs, but it indicates that the variable a has been destroyed, and normal a should store two characters, ending with\ 0. If the output is normal and does not prompt an error, it has something to do with the specific compiler, for example, the display of the result of vc will be delayed by 1 second, but dev-cPP will not.


strcpy () is a C standard function.
this function does not check for arrays that are out of bounds!

Menu