c-三重指针、数组和malloc



我的代码编译得很好,但在指针和数组概念上仍然有点粗糙。我非常感谢你的帮助。

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] = '';
        (*childIDs)[i] = NULL;
    }
}

您的示例没有显示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++那样有pass-by-refence

它是这样使用的:

void main ()
{
    char ** lines = 0;
    init2D (&lines, 4, 256); // char[256] x 4
}

相关内容

  • 没有找到相关文章

最新更新