1

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]);
chqrlie
  • 131,814
  • 10
  • 121
  • 189
GHOST mHBr
  • 15
  • 4

2 Answers2

0

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");
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

The first argument of the strcpy call is not a modifiable array of char, it is the array of char*, producing a type mismatch and unexpected behavior.

Modifying the code to strcpy(message[0], "Copy") would cause another problem as you would be trying to modify the string literal "Hello!000000000000" to which message[0] points.

If you just wish to modify the array element, just use a simple assignment to change the pointer:

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

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

Note that message is not a 3 dimensional array. It is an array of pointers to char. You could define it as an actual 2D array with the same initializer and the contents would be modifiable:

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

strcpy(&(message[0]), "Copy");
printf("%s", message[0]);
chqrlie
  • 131,814
  • 10
  • 121
  • 189