0

I am currently running into an issue trying to manipulate a 2D char array from an external function.

char* board[] = {
"first\r\n",
"second\r\n",
"third\r\n"
};

Later in the program, I want to manipulate an arbitrary single character in the array with

board[x][y] = 'A';

However when I reprint the board, the original values still persist. The desired outcome of

board[0][0] = 'A';

Should be:

Airst
Second
Third

However it still prints as the original "First", indicating that board's value never got changed. How do I fix this to update board's value?

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
BabyGates
  • 3
  • 1

2 Answers2

1

Your arrays contains pointers to string literals, which you cannot modify. Modifying a string literal yields undefined behaviour and in most cases they are also on read-only memory. You will need to have a 2-dim char array:

char board[][15] = {
    "first\r\n",
    "second\r\n",
    "third\r\n"
};

then you can safely do board[x][y] = 'A';

Note also that what you've declared is not a 2D char array. You've declared an array of char-pointers. What I've delcared is a 2D char array.

Pablo
  • 13,271
  • 4
  • 39
  • 59
1

The comment by @Stargateur points out the core problem.

literal string modification is implemented behavior and generally compile define it as undefined behavior.

Use:

char board[][100] = {
   "first\r\n",
   "second\r\n",
   "third\r\n"
};
R Sahu
  • 204,454
  • 14
  • 159
  • 270