Declaring a pointer to multidimensional array and allocating the array

前端 未结 6 435
名媛妹妹
名媛妹妹 2020-12-02 10:32

I\'ve tried looking but I haven\'t found anything with a definitive answer. I know my problem can\'t be that hard. Maybe it\'s just that I\'m tired..

Basically, I wa

6条回答
  •  醉话见心
    2020-12-02 10:58

    I suggest using a far simpler method than an array of arrays:

    #define WIDTH 3
    #define HEIGHT 4
    
    int* array = new int[WIDTH*HEIGHT];
    int x=1, y=2, cell;
    cell = array[x+WIDTH*y];
    

    I think this is a better approach than an array of an array, as there is far less allocation. You could even write a helper macro:

    #define INDEX(x,y) ((x)+(WIDTH*(y)))
    
    int cell = array[INDEX(2,3)];
    

提交回复
热议问题