gpt4 book ai didi

c - 关于从结构中获取字段作为字符串指针数组并将它们保存在字符串指针数组的实例变量中的问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:43:33 25 4
gpt4 key购买 nike

所以我有一个定义如下的结构

struct pastCommand
{

int numberOfCommand;
char *command;
char *commandslist[10];
int commandlistLength;
};

我写了一个可以按我想要的方式打印结构的函数

    void printHistoryElement(struct pastCommand *currentHistory)
{


if(currentHistory==NULL)
{


}
else
{
int myLength=currentHistory->commandlistLength;
int numberCommand=currentHistory->numberOfCommand;
char *myCommand=currentHistory->command;
char *currentList[] = currentHistory->commandslist;
printf("Commands #%d: %s\n",numberCommand, *myCommand);
for(int i=0; i<myLength; i++)
{

printf("arg[%d] :%s\n",i,currentList[i]);


}
printf("\n");
}


}

当我在这条线上遇到问题时

char *currentList[] = currentHistory->commandslist;

错误提示:数组初始值设定项必须是初始值设定项列表

我不确定到底是什么问题,它们是同一类型,一个指向字符串的指针数组,但是我不能指出这个问题。对此问题的一些见解将非常有帮助。谢谢。

最佳答案

声明中的空方括号 [] 语法用于定义数组,其大小由数组初始值设定项定义。但是,在您的代码中,您只是指向某个现有数组,因此您可以使用指针来完成。由于您的数组是指针数组,因此您需要一个指向指针的指针,如下所示:

char **currentList = currentHistory->commandslist;

其余代码保持不变。

请注意,虽然这可行,但完全没有必要将指向数组的指针存储在局部变量中。你可以在没有本地的情况下重写你的代码,像这样:

for(int i=0; i<myLength; i++)
{
printf("arg[%d] :%s\n", i, currentHistory->commandslist[i]);
}

关于c - 关于从结构中获取字段作为字符串指针数组并将它们保存在字符串指针数组的实例变量中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23585984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com