简体   繁体   中英

Convert string to array, strcpy don't work

i tryed to use this algorithm to convert a string to an array. the problem is this: strcpy don't work.

i tried also: strcpy_s strncpy memcpy --> with this function my array can print only the 1st word ( dunno why )...

string tmp;
getline(cin, tmp);
char* messaggio = new char[tmp.size()];
ZeroMemory(messaggio, tmp.size());
strcpy(messaggio, tmp.c_str());

tmp.resize(NULL);

i use Visual Studio 2013... when i try to use strcpy i have a strange error: C4996 may be unsafe. if i try with strcpy_s is the same, same with strncpy...

One problem in your code, is that string::size gives you the number of characters excluding the null termination. So messagio does not have enough room for a nul-terminated string, and strcpy will try to write beyond its bounds.

As for the warning, it is because strcpy makes it very easy to go out of bounds. If the length of the source string is greater than that of the destination buffer, you get undefined behaviour. The suggested alternatives give you means to protect yourself from that (but are not 100% fool-proof).

If what you want is an array-like object containing the characters of the string, then the idiomatic way to do this is to use a vector:

std::vector<char> messagio(tmp.begin(), tmp.end());

If you really want a character string, then just use std::string .

The error you got in fact is not an error. It is a warning. Maybe you set on the option of the compiler that forces the compiler to consider all warnings as errors.

Your code has a bug. The size of the allocated array shall be one greater than the size of the string that to accomodate the terminating zero used by function std::strcpy

So you should write

std::string tmp;
std::getline( std::cin, tmp );

char* messaggio = new char[tmp.size() + 1];
std::strcpy( messaggio, tmp.c_str() );

Or you could write

strcpy_s( messaggio, tmp.size() + 1, tmp.c_str() );

though function strcpy_s is not a standard C++ function. It is present only in the C Standard.

I am sure you should ignore this warning.

If your compiler supports class std::dynarray you could use it instead of the raw pointer.

For example

std::dynarray<char> messagio( tmp.size() + 1 );
std::strcpy( messagio.data(), tmp.c_str() ); 

[SOLVED]

thx at all, expecially to "Vlad from Moscow" :3

std::string tmp;
        tmp.resize(0);
        std::getline(std::cin, tmp);
        char* messaggio = new char[tmp.size()+1];

        strcpy_s(messaggio, tmp.size()+1, tmp.c_str());

        send(ConnectSocket, messaggio, tmp.size()+1, NULL); //Send 2

        tmp.resize(0);
        delete messaggio;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM