char数组的指针数组

ant*_*009 1 c pointers

gcc 4.4.4 c89

但是,我在尝试显示所有动物时遇到问题.

我有以下代码.

我正在尝试显示阵列中的所有动物.所以我有三个指向char*的指针数组.然后是指向这些数据集的指针数组.

我试图控制内循环以检查外部的-1和NULL.

void initialize_char_array()
{
    char *data_set1[] = {"dog", "cat", "bee", NULL};
    char *data_set2[] = {"rabbit", "ant", "snake", "rat", NULL};
    char *data_set3[] = {"cow", "lizard", "beaver", "bat", "hedgehog", NULL};

    char *ptr_char[] = {*data_set1, *data_set2, *data_set3, NULL};

    display_char_array(ptr_char);
}

void display_char_array(char **ptr_char)
{
    size_t inner = 0, outer = 0;

    for(outer = 0; ptr_char[outer] != NULL; outer++) {
        for(inner = 0; *ptr_char[inner] != -1; inner++) {
            printf("data [ %s ]\n", ptr_char[outer][inner]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢任何建议,

pha*_*dej 5

*data_set1 is the same as data_set1[0]. Here's a fixed version of what you trying to do. IMHO it's matter of taste which are you using: index-variable or pointer-iterators in the loop, apparently compiler will generate the very same machine code.

// type of ptr_char changed
void display_char_array(char **ptr_char[])
{
    size_t inner = 0, outer = 0;

    for(outer = 0; ptr_char[outer] != NULL; outer++) {
        // check for NULL in inner loop!
        for(inner = 0; ptr_char[outer][inner] != NULL; inner++) {
            printf("data [ %s ]\n", ptr_char[outer][inner]);
        }
    }
}
void initialize_char_array()
{
    char *data_set1[] = {"dog", "cat", "bee", NULL};
    char *data_set2[] = {"rabbit", "ant", "snake", "rat", NULL};
    char *data_set3[] = {"cow", "lizard", "beaver", "bat", "hedgehog", NULL};

    // fixed
    char **ptr_char[] = {data_set1, data_set2, data_set3, NULL};

    display_char_array(ptr_char);
}
Run Code Online (Sandbox Code Playgroud)