gpt4 book ai didi

c - 简单的 C 问题 : compare first char of a char array

转载 作者:太空宇宙 更新时间:2023-11-04 07:42:01 24 4
gpt4 key购买 nike

如何比较char**第一个元素的首字母?

我试过:

int main()
{
char** command = NULL;
while (true)
{
fgets(line, MAX_COMMAND_LEN, stdin);
parse_command(line, command);
exec_command(command);
}
}

void parse_command(char* line, char** command)
{
int n_args = 0, i = 0;
while (line[i] != '\n')
{
if (isspace(line[i++]))
n_args++;
}

for (i = 0; i < n_args+1; i++)
command = (char**) malloc (n_args * sizeof(char*));

i = 0;
line = strtok(line," \n");
while (line != NULL)
{
command[i++] = (char *) malloc ( (strlen(line)+1) * sizeof(char) );
strcpy(command[i++], line);
line = strtok(NULL, " \n");
}
command[i] = NULL;
}

void exec_command(char** command)
{
if (command[0][0] == '/')
// other stuff
}

但这会导致段错误。我做错了什么?

谢谢。

最佳答案

您可以粘贴更多代码吗?您是否为 char* 数组和 char* 数组的元素分配了内存?

关于c - 简单的 C 问题 : compare first char of a char array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2936666/

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