Search code examples
cstringstrcpy

strcpy problem with two dimension array in C


I'm trying to copy a string to an array of strings using the strcpy function but it doesn't work!

Here is the code:

char *message[10] = { "Hello!000000000000", "Good Bye!", "1202", "hel", "beh", "cheshm" };
char *dst = "Copy";

strcpy(&(message[0]), "Copy");
printf("%s", message[0]);

Solution

  • You have two problems:

    1. strcpy expects a destination argument of type char *. But since message[0] is a char * then &message[0] is a pointer to that pointer which have the type char **. In other words, you pass the wrong pointer as the destination. That leads to undefined behavior.

    2. The second problem happens when you fix the first, and that is you have to remember that literal strings are not modifiable. They are in effect read-only. And you try to copy a string into the literal string that message[0] is pointing to. Attempting to modify a literal string also leads to undefined behavior.

    The solution to the second problem is to use an array of arrays of char:

    char message[][256] = { ... };
    

    The solution to the first problem is to simply pass message[0]:

    strcpy(message[0], "Copy");