初始化静态多维以空结尾的数组



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

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

void print_commands(char *commands[][])
{
    int i, j;
    char *command[];
    for(i = 0; commands[][i] != NULL; i++)
    {
        command = commands[][i];
        printf("Command #%d: %sn", i, command[0]);
        for(j = 1; command[j] != NULL; j++)
        {
            printf("Argument #%d: %sn", 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 );
}

如何正确初始化和使用这类数据?

谢谢!

因为数组不是指针,所以不能用NULL初始化数组。为什么不选择全零结构体这个如此常见和习惯的原则呢?

char *commands[][5] = {
    { "less", NULL },
    { "sort", NULL },
    { "cat", "my.txt", NULL },
    { "echo", "hello", NULL },
    { NULL }
};
void print_commands(char **commands[])
{
    int i, j;
    char **command;
    for(i = 0; commands[i] != NULL; i++)
    {
        command = commands[i];
        printf("Command #%d: %sn", i, command[0]);
        for(j = 1; command[j] != NULL; j++)
        {
            printf("Argument #%d: %sn", 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: %sn", i, command[0]);
        for(j = 1; command[j] != NULL; j++)
        {
            printf("Argument #%d: %sn", 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 );
}

相关内容

  • 没有找到相关文章

最新更新