Allocating an 2D array in C in heap instead of stack

I have not realized that there is a difference between stack an heap allocation in C. I have written a seriously big program in with stack allocated arrays, but obviously they are not sufficiently big to store the read data. Thus, I need to rewrite everything with malloc allocation. Is there a clever way how 2D arrays can be allocated dynamicaly to heap, and their usage in the code to be similar so the stack allocated, meaning that:

My code looks something like this:

int MM,NN;
float Edge[MM][NN];
Do_Something(MM,NN,Edge);

The procedure that is called is defined as:

void Do_Something(int MM,int NN,float Edge[MM][NN]);

I need to rewrite everything with malloc so that these definitions are still valid. Is this possible?


Yes, use pointers to arrays:

int (*pa)[x] = malloc( sizeof(*pa) * y ) ;

Where x and y are inner and outer dimensions. This is is similar in usage to int pa[y][x] . You can use this pointer in your functions.


In theory, there is nothing wrong with your code. The C standard says it is OK.

However, in practice, common implementations only set aside a relatively small space for stack variables and they don't do any overflow checks. It would be easy for a compiler to store your array somewhere else than the call stack, or to increase the size of that stack; however common compilers just don't do that ; they expect you to manually request such things.

You can force heap allocation by writing instead:

float (*Edge)[NN] = malloc(MM * sizeof *Edge);

If you are not familiar with this malloc idiom then see here. Of course you will have to make sure that you do free(Edge); when you are done.

You can access this array's elements and pass it to a function in just the same way you are currently doing; it is only the initial allocation line that needs to change.

链接地址: http://www.djcxy.com/p/14128.html

上一篇: 虽然在F#或尾递归,什么时候使用?

下一篇: 用堆而不是堆栈在C中分配二维数组