问题描述
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","improve","your","question"},{"and","found","none."}}
我希望 args 成为
{"and","none."}
我该怎么做?
我尝试使用 args = strlist[someIndex];
但收到错误消息,提示 incompatible types when assigning to type ‘char *[100]’ from type ‘char (*)[100]’
,strcpy
似乎也失败了(可能是由于 args
没有分配足够的空间? ),我应该怎么做才能正确分配 args
?
编辑:args
已在赋值之前使用,因此更改 args
的类型虽然合理,但确实需要对代码的其他部分进行大量额外工作。
解决方法
您可以使用指向数组的指针:
char (*args)[CONST_C] = strList[2];
现在代码:
puts(args[0]);
puts(args[1]);
puts(args[2]);
将产生:
and
found
none.
,
您现在拥有的是一个指针数组,更好的选择是指向数组的指针:
#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","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.
如果你想使用你原来的指针数组,你也可以这样做,但是赋值也必须是手动,也就是说,你需要遍历数组来使分配,例如:
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
...
但是像第一个例子那样迭代指针是不可能的,数组的维度是正确迭代所必需的,因此需要一个指向数组的指针。