在我的程序中,函数read_commands
只获取2个字符串,并将其放入结构体Commands
中,然后返回填充的结构体
显然我的逻辑有些错误。我得到错误:
1 的读取大小无效
在山谷里。
typedef struct{
Command *test
Command *compile
}Commands;
typedef struct Command{
char *command;
struct Command *next;
}Command;
我只是做read_commands("abc", "abc");
我的代码的其余部分:
Commands read_commands(const char *compile_cmds, const char *test_cmds) {
Commands commands;
Command *compile, *test;
int i;
if (compile_cmds == NULL || test_cmds == NULL)
exit(0);
compile = commands.compile;
test = commands.test;
i = 0;
while (compile_cmds + i != NULL) {
compile = malloc(sizeof(Command));
compile->command = malloc(strlen((compile_cmds + i) + 1));
strcpy(compile->command, compile_cmds + i);
compile = compile->next;
i++;
}
i = 0;
while (test_cmds + i != NULL) {
test = malloc(sizeof(Command));
test->command = malloc(strlen((test_cmds + i) + 1));
strcpy(test->command, test_cmds + i);
test = test->next;
i++;
}
return commands;
}
您应该更改参数以接受多个命令,例如
Commands read_commands(const char** compile_cmds, const char** test_cmds)
然后你用来称呼它
char* compileCmds[] = { "abc", NULL };
char* testCmds[] = { "abc", NULL };
Commands c = read_commands(compileCmds,testCmds);
同时在您的函数中获取所有"编译"命令:
Commands commands = { NULL, NULL };
...
Command* last = NULL;
for (i = 0; compile_cmds[i] != NULL; ++i)
{
compile = malloc(sizeof(Command));
// check if we have added before, or if it is the first compile command
if (last!=NULL)
{
// last command, so append
last->next = compile;
}
else
{
// first command, set as first
commands->compile = compile;
}
// add the payload
compile->command = strdup(compile_cmds[i]);
compile->next = NULL;
// keep track of last to easy append
last = compile;
}
...
您可能已经注意到您的函数中有重复的代码,因此一个想法是一次为其中一个编译或测试创建一个函数readcommands,然后调用它两次。
例如
read_commands(Command** cmd, const char** cmds);
...
Commands c = {NULL,NULL};
read_commands(&c.compile, compileCmds);
read_commands(&c.test, testCmds);
额外的*是为了能够改变指针指向的内容
read_commands(Command** pc, const char* cmds)
{
...
*pc = malloc(sizeof(Command));
...
}