two dimensional array via pointer

后端 未结 4 568
情书的邮戳
情书的邮戳 2021-01-07 16:11

I would like to create a dynamic array which store permutation sequence, such that

order[0][]={1,2,3}
order[1][]={2,1,3}
order[2][]={2,3,1}

4条回答
  •  猫巷女王i
    2021-01-07 16:23

    The code sample only simulates a multidimensional array, and does it incorrectly. To see what's going wrong, start by considering what happens when you declare a multidimensional array:

    int foo[3][5];
    

    This allocates a contiguous region of memory of size 3*5*sizeof(int). In an expression such as foo[i], the foo is converted to a int [5] pointer, then the index operator is applied. In other words, foo[i] is equivalent to *( (int (*)[5])foo) + i). Each foo[i] would be considered as having size 5*sizeof(int).

       x,y:  0,0 0,1 0,2 0,3 0,4 1,0 
    foo --> | 1 | 2 | 3 | 4 | 5 | 1 |...
            <- 5 * sizeof(int) ->
    

    When you create x in the sample code, you're replicating this type of multidimensional array. The index expression you're using (*(order + y + x)) is thus wrong, as it doesn't properly handle the size of order[y]: order + 1 + 0 == order + 0 + 1, which is the problem you're seeing in the sample output.

    The correct expressions are: (order + num_term * y) for the yth permutation and *(order + num_term * y + x) for element order[y][x].

    This suggests another class of error in the sample. For this kind of simulated multidimensional array, the array types are actually pointers to single dimensional arrays. The declared types of x and order should be int*, not int**. This should be reinforced by the type warnings the sample code should generate:

    • when allocating space for x, the type of the pointer (int*) doesn't match the type of x
    • when printing the elements of x, the type of *(x+y+z) doesn't match the format "%d".

    However, while simulating a multidimensional array saves space, it's more error prone when used (unless you write a function to handle indexing). A solution such as Als' may be safer, as you can use the standard indexing operator.

提交回复
热议问题