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

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

我有一个这样创建的 char* 二维数组:

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

然后我想改变这个数组中的一个字符。以我有限的经验,我会这样做:

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

而且我希望“A1”变为“G1”。相反,我得到了一个段错误。 我该怎么做?

这个声明

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

声明一个 multi-dimensional 指向字符串文字的指针数组。

您不能更改字符串文字。任何更改字符串文字的尝试都会导致未定义的行为。

来自 C 标准(6.4.5 字符串文字)

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

按以下方式声明字符串数组

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

请注意,因为数组的第二个维度等于 4,而您只为 sub-arrays 指定了三个初始值设定项,那么声明看起来像

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

现在你可以写了

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

如果你知道所有字符串的长度都是 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"

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

如果您想支持不同大小的字符串,您也可以使用 malloc 创建您的字符串。如果您想了解更多详情,请告诉我。