1

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?

suszterpatt
  • 8,187
  • 39
  • 60
Mojusko
  • 13
  • 3

2 Answers2

2

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.

2501
  • 25,460
  • 4
  • 47
  • 87
  • I did as you suggested, I changed all the definitions from int pa[x][y]; to int (*pa)[x] = malloc( sizeof(*pa) * y ) ; However, my code is not working as it was. Is there a difference in indexing? Difference in memory allocation? – Mojusko Nov 12 '14 at 11:42
  • I figured it out. The error was due to deallocation. – Mojusko Nov 12 '14 at 12:57
1

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.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365