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

标签 c arrays

如何比较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/

相关文章:

ios - 加入具有不同最终定界符的字符串数组

c - 从文件中读取两个数组

javascript - 比较两个数组对象并找到唯一值

在我的 c 代码中找不到错误

c - while循环中的if语句不起作用

c++ - 使用 win32 或其他库导入 .reg 文件

C - 结构段错误

c - 为什么将数组分配给矩阵是非法的?

arrays - Swift 2.2 中的多维数组 removeAtIndex

javascript - 交换任意 3D 数组值