How can a double pointer be used for a two dimensional matrix?

心已入冬 提交于 2019-12-06 11:46:07

A common way to do this is described in http://c-faq.com/aryptr/dynmuldimary.html

You can simply allocate the space and cast the pointer to the type which defines the col and row sizes. Looking up a pointer via [][] is expensive. And building a dynamic multi dimensional array this way should be reserved for ragid arrays.. IE: only use it when necessary.

You can define a type:

typedef int MyArray[20][20];

And then cast the malloc pointer to the type you want:

MyArray * curr_gen = (MyArray *) malloc(...);

However this assumes that you have a constant, known at compile time height and width. If it must be dynamic then by all means use the index into a pointer table method. But keep in mind that the actual pointer looked up must be loaded at the last possible minute leading to Pipeline stalls, and potential cache misses. Making it 100 times more expensive than just doing the math yourself via [row * 20 + col].

So the real question you should ask yourself is "Does it need to run fast, or do I want the code to look 'Neat'?"

You can just use int* as the type of grid in my way.

Convert the 2D position to 1D by a macro define or a function:

#define MATRIX2INDEX(x, y, width)  ((x) + (y) * (width))  // `width` is the max of x + 1 :)
int Matrix2Index(int x, int y, int width)
{
    return MATRIX2INDEX(x, y, width);
}

Visit the data by 2D position in int*:

int* grid = (int*)malloc(sizeof(int) * WIDTH * HEIGHT);
grid[MATRIX2INDEX(0, 0, WIDTH)] = 0; // here: get the data you want by 2D position
free(grid); grid = NULL;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!