简体   繁体   中英

Changing a character of a string in a 2D string array causes Segmentation fault

I have a 2D array of char* created like this :

char *rows[][4] = {
    {"A1","A2","A3"},
    {"B1","B2","B3"}
};

Then i want to change an char in this array. With my limited experience i would do it like this :

rows[0][0][0] = 'G';

And I'd expect the "A1" to change to "G1". Instead i get a Seg fault. How do I do this ?

This declaration

char *rows[][4] = {
    {"A1","A2","A3"},
    {"B1","B2","B3"}
};

declares a multi-dimensional array of pointers to string literals.

You may not change a string literal. Any attempt to change a string literal results in undefined behavior.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined

Declare the array of strings the following way

char rows[][4][3] = {
    {"A1","A2","A3"},
    {"B1","B2","B3"}
};

Pay attention to that as the second dimension of the array is equal to 4 while you specified only three initializers for sub-arrays then the declaration looks like

char rows[][4][3] = {
    {"A1","A2","A3", ""},
    {"B1","B2","B3", ""}
};

Now you may write

rows[0][0][0] = 'G';

If you know all the strings will be length 2, you can use this:

  char rows[2][3][3] = {
    {"A1","A2","A3"},
    {"B1","B2","B3"}
  };
  printf("%c\n", rows[0][0][0]); //Prints "A"
  printf("%s\n", rows[0][0]); //Prints "A1"

  rows[0][0][0] = 'G';

  printf("%c\n", rows[0][0][0]); //Prints "G"
  printf("%s\n", rows[0][0]); //Prints "G1"

Note that you need rows[2][3][3] instead of rows[2][3][2] when the string are of length 2 because in c every string ends with the '\\0' character.

If you want to support strings of different sizes, you also could create your strings using malloc . Let me know if you want more details about this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM