How do I correctly set up, access, and free a multidimensional array in C?

后端 未结 5 958
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 23:31

I have seen dozens of questions about “what’s wrong with my code” regarding multidimensional arrays in C. For some reason people can’t seem to wrap their head around what is

5条回答
  •  终归单人心
    2020-11-21 23:55

    If you want to use a typedef'd array, it is even simpler.

    Say you have in your code typedef int LabeledAdjMatrix[SIZE][SIZE];

    You can then use:

    LabeledAdjMatrix *pMatrix = malloc(sizeof(LabeledAdjMatrix));
    

    Then you can write:

    for (i=0; i

    Because pArr is a pointer to you matrix and * has lower priority than [];

    That is why a mode common idiom is to typedef the row:

    typedef int LabeledAdjRow[SIZE];
    

    Then you can write:

    LabeledAdjRow *pMatrix = malloc(sizeof(LabeledAdjRow) * SIZE);
    for (i=0; i

    And you can memcpy all that directly:

    LabeledAdjRow *pOther = malloc(sizeof(LabeledAdjRow) * SIZE);
    memcpy(pOther, pMatrix, sizeof(LabeledAdjRow) * SIZE);
    

提交回复
热议问题