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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments