0

我的代码编译得很好,但我对指针和数组的概念还是有点粗略。非常感谢您的帮助。

void initialize(int individual_count, int family_count, char ***indiIDs,
                char ***names, char ***spousesIDs, char ***childIDs)
//so here I declared two int variables and four triple pointers,
// which are pointer to a pointer to a pointer to an integer, correct?
{
    int i;

    //malloc allocates memory space and returns the address of the
    // first byte to the pointer *indiIDs,right?

    (*indiIDs) = (char**)malloc(sizeof(char*) * individual_count);
    (*names) = (char**)malloc(sizeof(char*) * individual_count);
    for(i = 0; i <individual_count; i++)
    {
        (*indiIDs)[i] = (char*)malloc(sizeof(char) * 20);
        (*names)[i] = NULL;
    }

    //*indiIDs[i] is an array of pointers, correct? so what exactly
    //  is the difference between mallocing and returning to *indiIDs
    //  and then to *indiIDs[i] as seen here?

    (*spousesIDs) = (char**)malloc(sizeof(char*) * family_count);
    (*childIDs) = (char**)malloc(sizeof(char*) * family_count);
    for(i = 0; i < family_count; i++)
    {
        (*spousesIDs)[i] = (char*)malloc(sizeof(char) * 40);

        //since spousesIDs[][] is a 2D array, would *spousesIDs[][]
        // indicate a triple array then?

        (*spousesIDs)[i][0] = '\0';
        (*childIDs)[i] = NULL;
    }
}
4

1 回答 1

0

您的示例不显示 3D 数组,而是显示 2D 数组:

void init2D(char * ** x, int w, int h)
{
    (*x) = (char**)malloc(sizeof(char*) * w);

    for (i=0; i<w; i++) (*x)[i] = (char*)malloc(sizeof(char) * h);
}

它有一个额外的 * 作为函数参数的原因是因为 C不像 C++ 那样具有传递引用

它是这样使用的:

void main ()
{

    char ** lines = 0;

    init2D (&lines, 4, 256); // char[256] x 4

}
于 2013-03-29T14:55:00.427 回答