我试图在一个函数中创建2D数组,并保留它供以后使用。我有这个:
char **add_to_list(char *str) {
char list[4][7];
int i = 0;
while (i < 4) {
if (i == 1) {
strcpy(list[i], str);
}
else {
strcpy(list[i], "diff_str");
}
i++;
}
return list;
}
int main() {
char **list[4][7];
char *str = "string";
**list = add_to_list(str);
}
但是当add_to_list返回时,list不是我所期望的
试试这个。我简化了它,因为你使用的是静态分配矩阵。我还指出,在else子句中添加的新字符串大于7。如。"diff_str"
。它的8个字符加上结束NULL字节的1。因此,我将静态分配的大小从7调整为9。祝你继续学习c。
void add_to_list(char ppList[4][9], char *str) {
int i = 0;
while (i < 4) {
if (i == 1) {
strcpy(ppList[i], str);
}
else {
strcpy(ppList[i], "diff_str"); // this string is 9 chars when
// counting NULL terminating byte
}
i++;
}
}
int main() {
// adjusted size of bytes used to hold string
char list[4][9] = {"one", "two", "three", "four"};
char *str = "string";
printf("str is %sn", str);
printf("list[0] is %sn", list[0]);
printf("list[1] is %sn", list[1]);
printf("list[2] is %sn", list[2]);
printf("list[3] is %sn", list[3]);
add_to_list(list, str);
printf("list[0] is %sn", list[0]);
printf("list[1] is %sn", list[1]);
printf("list[2] is %sn", list[2]);
printf("list[3] is %sn", list[3]);
}
运行后如下所示:
str is string
list[0] is one
list[1] is two
list[2] is three
list[3] is four
list[0] is diff_str
list[1] is string
list[2] is diff_str
list[3] is diff_str