多维char数组和指针赋值

Multi-dimensional char array and pointer assignment

假设我有一个 3 维字符数组

char strList[CONST_A][CONST_B][CONST_C];

和一个数组指针(评论指出错误后改):

char * args[CONST_C];

我想选择 strList 的一部分并使 args 成为该值。例如,如果 strList 表示

{{"Your", "question", "is", "ready", "to", "publish!"},
 {"Our", "automated", "system", "checked", "for", "ways", "to", "improve", "your", "question"},
 {"and", "found", "none."}}

我希望 args 是

{"and", "found", "none."}

我应该怎么做?

我试过使用 args = strlist[someIndex]; 但得到一个错误说 incompatible types when assigning to type ‘char *[100]’ from type ‘char (*)[100]’ strcpy 似乎也失败了(可能是由于 args 没有分配足够的space?), 我应该怎么做才能正确分配 args?

编辑:args 已在分配之前使用,因此更改 args 的类型虽然有道理,但确实需要对代码的其他部分进行大量额外工作。

您可以使用指向数组的指针:

char (*args)[CONST_C] = strList[2];

现在代码:

    puts(args[0]);
    puts(args[1]);
    puts(args[2]);

将产生:

and
found
none.

您现在拥有的是一个指针数组,更好的选择是指向数组的指针:

Live demo

#include <stdio.h>

#define CONST_A 5
#define CONST_B 10
#define CONST_C 15

int main(void) {
  char strList[CONST_A][CONST_B][CONST_C] = {
      {"Your", "question", "is", "ready", "to", "publish!"},
      {"Our", "automated", "system", "checked", "for", "ways", "to", "improve",
       "your", "question"},
      {"and", "found", "none."}};

  char(*args)[CONST_C] = strList[2];

  for (size_t i = 0; i < 3; i++) {
    printf("%s ", args[i]);
  }
}

输出:

and found none. 

如果你想使用你原来的指针数组,你也可以这样做,但是赋值也必须是手动之类的,你需要迭代在数组上进行分配,例如:

Live demo

char *args[3];

for (int i = 0; i < 3; i++)
{
    args[i] = strList[2][i];
}

就像你在评论中问的那样,你可以有一个指向其中一个字符串的 char 指针,例如:

char *args = strList[2][0]; // and
args = strList[2][1];       // found
...

但是不可能像第一个示例那样迭代指针,数组的维数对于正确的迭代是必需的,因此需要指向数组的指针。