How are multi-dimensional arrays formatted in memory?

前端 未结 6 1394
名媛妹妹
名媛妹妹 2020-11-22 03:51

In C, I know I can dynamically allocate a two-dimensional array on the heap using the following code:

int** someNumbers = malloc(arrayRows*sizeof(int*));

fo         


        
6条回答
  •  不要未来只要你来
    2020-11-22 04:36

    The answer is based on the idea that C doesn't really have 2D arrays - it has arrays-of-arrays. When you declare this:

    int someNumbers[4][2];
    

    You are asking for someNumbers to be an array of 4 elements, where each element of that array is of type int [2] (which is itself an array of 2 ints).

    The other part of the puzzle is that arrays are always laid out contiguously in memory. If you ask for:

    sometype_t array[4];
    

    then that will always look like this:

    | sometype_t | sometype_t | sometype_t | sometype_t |
    

    (4 sometype_t objects laid out next to each other, with no spaces in between). So in your someNumbers array-of-arrays, it'll look like this:

    | int [2]    | int [2]    | int [2]    | int [2]    |
    

    And each int [2] element is itself an array, that looks like this:

    | int        | int        |
    

    So overall, you get this:

    | int | int  | int | int  | int | int  | int | int  |
    

提交回复
热议问题