Ali Raza Abbasi
Ali Raza Abbasi

Reputation: 31

Convert string to character array, but strcpy() gives an error

Consider:

void takeInput()
{
    string word;
    cin >> word;

    int n = word.length();

    // Declaring character array
    char *char_array = new char [n + 1];

    // Copying the contents of the
    // string to char array
    strcpy(char_array, word.c_str());

    for (int i = 0; i<n; i++)
        cout << char_array[i];
}

error : Severity Code Description Project File Line Suppression State Error C4996 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. DSPROJECT c:\users\hp\source\repos\dsproject\dsproject\source.cpp 49

Upvotes: 2

Views: 1369

Answers (2)

no one special
no one special

Reputation: 1764

rather than strcpy you can use strncpy:

strncpy(char_array, word.c_str(), n + 1);

This n+1 ensures that the terminating '\0' will be copied as well, and the memory buffer you already have big enough.

Or, you can disable this warning (which of course is highly NOT recommended) with defining _CRT_SECURE_NO_WARNINGS before using strcpy i.e.:

#define _CRT_SECURE_NO_WARNINGS

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Strictly speaking, this is not an error, it's a warning treated as an error. The reason for the warning is explained in the error message: strcpy is unsafe because it can go past the limits of the destination string.

The message suggests two ways of addressing this - (1) using strcpy_s, or (2) turning off the warning (not recommended).

C++ has another approach that would fix the compile error - using std::copy function from the Standard C++ library, then null-terminating the result:

char *char_array = new char [n + 1];
std::copy(word.begin(), word.end(), char_array);
char_array[n] = '\0';

Upvotes: 1

Related Questions