gpt4 book ai didi

c - 返回一个指向结构体的指针,该结构体中有一个 char ** 指针到指针

转载 作者:行者123 更新时间:2023-11-30 21:02:03 27 4
gpt4 key购买 nike

我只是无法理解,我应该如何返回一个包含双指针的结构......当我尝试时它会在同一函数中打印正确的值......但是当我在 i 之后打印时会打印垃圾值将其返回到主...

struct arguments{
char **argv;
int argc;
};

这是结构。

struct arguments * shell_make_argu(char *line)
{
struct arguments *data=malloc(sizeof(struct arguments));
int bufsize = word_BUFSIZE , i;
data->argc = 0;
data->argv = malloc(bufsize * sizeof(char*));
char *word;

if (!data->argv) {
fprintf(stderr, "shell memory allocation error\n");
exit(EXIT_FAILURE);
}

word = strtok(line, word_separater);
while (word != NULL) {
data->argv[data->argc] = word;
data->argc++;

if (data->argc >= bufsize) {
bufsize += word_BUFSIZE;
data->argv = realloc(data->argv, bufsize * sizeof(char*));
if (!data->argv) {
fprintf(stderr, "shell memory allocation error\n");
exit(EXIT_FAILURE);
}
}

word = strtok(NULL, word_separater);
}
data->argv[data->argc] = NULL;
for(i=0;i<data->argc;i++)
printf("Command was: %s\n",data->argv[i]);
return data;
}

这就是我在 main 中接收结构的方式......

int main(int argc,char **argv)
{
struct arguments *data = malloc(sizeof(struct arguments));
char *line;
int status = 1 , i;
do {
printf("T_Shell>> ");
line = shell_take_input();
if(line != '\0' && strcmp(line,"found ctrl_D") != 0){
data = shell_make_argu(line);
free(line);
for(i=0;i<data->argc;i++)
printf("Command was: %s\n",data->argv[i]);
shell_execute_comand(data->argc,data->argv);
}
else if(line == '\0')
printf("\n");
else
break;
} while (status);
system("clear");
return 0;
}

最佳答案

main 函数中打印 data->argv 之前,您对 line 进行了 free 操作,这是不好的,因为data->argv 的每个元素都指向 line 指向的缓冲区。

调用shell_execute_comand后执行free,或者分配新内存并复制strtok返回的字符串,而不是分配strtok 的返回值直接返回到 data->argv 的元素。

关于c - 返回一个指向结构体的指针,该结构体中有一个 char ** 指针到指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33327510/

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