2

我想初始化一个以空结尾并包含静态以空结尾的数组的静态数组。我还希望能够在以后打印所有内容。

这是我到目前为止的代码,显然初始化和数据类型不正确

void print_commands(char *commands[][])
{
    int i, j;
    char *command[];

    for(i = 0; commands[][i] != NULL; i++)
    {
        command = commands[][i];
        printf("Command #%d: %s\n", i, command[0]);
        for(j = 1; command[j] != NULL; j++)
        {
            printf("Argument #%d: %s\n", j, command[j]);
        }
    }
}

int main(int argc, char *argv[])
{
    char *commands[][5] = {
        {"less", 0}, 
        {"sort", 0}, 
        {"cat", "my.txt", 0},
        {"echo", "hello", 0}, 
        NULL};

    print_commands(commands);

    exit( 0 );
}

我将如何正确初始化和使用这种数据?

谢谢!

4

2 回答 2

2

由于数组不是指针,因此您不能使用NULL. 为什么不选择全零结构如此普遍和惯用的原理呢?

char *commands[][5] = {
    { "less", NULL },
    { "sort", NULL },
    { "cat", "my.txt", NULL },
    { "echo", "hello", NULL },
    { NULL }
};
于 2013-04-16T17:56:28.003 回答
1
void print_commands(char **commands[])
{
    int i, j;
    char **command;

    for(i = 0; commands[i] != NULL; i++)
    {
        command = commands[i];
        printf("Command #%d: %s\n", i, command[0]);
        for(j = 1; command[j] != NULL; j++)
        {
            printf("Argument #%d: %s\n", j, command[j]);
        }
    }
}

int main(int argc, char *argv[])
{
    char **commands[] = {
        (char*[]){"less", 0}, 
        (char*[]){"sort", 0}, 
        (char*[]){"cat", "my.txt", 0},
        (char*[]){"echo", "hello", 0}, 
        NULL};

    print_commands(commands);

    exit( 0 );
}

或者

void print_commands(char *commands[][5])
{
    int i, j;
    char **command;

    for(i = 0; *commands[i] != NULL; i++)
    {
        command = commands[i];
        printf("Command #%d: %s\n", i, command[0]);
        for(j = 1; command[j] != NULL; j++)
        {
            printf("Argument #%d: %s\n", j, command[j]);
        }
    }
}

int main(int argc, char *argv[])
{
    char *commands[][5] = {
        {"less", 0}, 
        {"sort", 0}, 
        {"cat", "my.txt", 0},
        {"echo", "hello", 0}, 
        { NULL }
    };

    print_commands(commands);

    exit( 0 );
}
于 2013-04-16T18:04:25.853 回答