-1

I'm building a game, and when I change the value in 2d-map using the following code

char example[100];
strcpy(example, " ");
strcat(example, player1->unitName[j]);
strcat(example, " ");
map->map[x][y] = example;

the whole values I put with example in map change.

I guess I'm putting the pointer to the example.

Is there any way I can put just the value of example not the address or pointer?

Mirakurun
  • 4,859
  • 5
  • 16
  • 32
Lebanner
  • 77
  • 1
  • 1
  • 9

1 Answers1

5

You should allocate new buffer for each elements and copy the contents like this.

char example[100], *buffer;
strcpy(example, " ");
strcat(example, player1->unitName[j]);
strcat(example, " ");
buffer = malloc(strlen(example) + 1); /* +1 for terminating null-character */
if (buffer != NULL) {
    strcpy(buffer, example);
} else {
    /* handle error */
}
map->map[x][y] = buffer;

You can use strdup() if it is available in your system.

char example[100];
strcpy(example, " ");
strcat(example, player1->unitName[j]);
strcat(example, " ");
map->map[x][y] = strdup(example);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 1
    +1. Don't forget to free the memory. Another example would be to have a three dimensional array: `map->map[x][y][100] = "Who's your daddy?";`. But of course, this is considered a bad practice due to memory wasting. – Andrejs Cainikovs Jun 07 '16 at 16:52
  • @AndrejsCainikovs Not knowing the actual definition, your example looks like performing out-of-range access and meaningless pointer-to-integer conversion. Shouldn't it be `strcpy(map->map[x][y], "Who's your daddy?");`? – MikeCAT Jun 07 '16 at 16:54
  • Oops. Apologies. Too much Python at work. Started to mess things up :) – Andrejs Cainikovs Jun 07 '16 at 16:56