简体   繁体   English

更改二维字符串数组中字符串的字符会导致分段错误

[英]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* 二维数组:

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".我希望“A1”变成“G1”。 Instead i get a Seg fault.相反,我得到了一个 Seg 错误。 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)来自 C 标准(6.4.5 字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. 7 如果这些数组的元素具有适当的值,则未指定这些数组是否不同。 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请注意,因为数组的第二维等于4而您只为子数组指定了三个初始化器,那么声明看起来像

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:如果您知道所有字符串的长度为 2,则可以使用以下命令:

  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.请注意,当字符串长度为 2 时,您需要行 [2][3][3] 而不是行 [2][3][2],因为在 c 中每个字符串都以 '\\0' 字符结尾。

If you want to support strings of different sizes, you also could create your strings using malloc .如果你想支持不同大小的字符串,你也可以使用malloc创建你的字符串。 Let me know if you want more details about this.如果您想了解更多详情,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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