I'm pretty new with C and just confused with what's really happening when I'm passing 2D arrays allocated in HEAP memory into a function. I've written code which has three functions, A, B, C which demonstrates my question.
Essentially, when I create a 2d array in stack space in function-A, I am able to pass that 2d array pointer to a function-B which requires the parameter (int size, int (*arr)[size]) and that works fine. My understanding is the 'int size' variable is required to let arr pointer now how much space it should jump each increment
However, when I create a 2d array in HEAP space in function-A, passing it to function-B appears to lose the location of the data (see code). However if I pass this HEAP space 2d array to function-C which has the parameter (int **arr), it works fine.
It would be great if someone could try to explain why I don't need to specify size when passing the HEAP space 2d array into function-C. Also, when I pass the 2d array created in STACK space to function-C, it crashes, why is that?
Here is sample code showcasing my question (Output is this):
#include <stdio.h>
#include <stdlib.h>
void function_A(int num)
{
// allocating HEAP space for 2D array
int **arrHEAP = (int **)malloc(2*sizeof(int*));
arrHEAP[0] = (int *)malloc(5*sizeof(int));
arrHEAP[1] = (int *)malloc(5*sizeof(int));
for(int i=0;i<2;i++) // initialising
for(int j=0;j<5;j++)
arrHEAP[i][j] = num++;
function_B(5, arrHEAP); // prints random data
function_C(arrHEAP); // prints correctly, works
// allocating STACK space for 2D array and initialising
int arrSTACK[2][5] = {{100, 200, 300, 400, 500},{600,700,800,900,1000}};
function_B(5, arrSTACK); // prints correctly, works
//function_C(arrSTACK); // if I were to run this it crashes the program, why?
}
void function_B(int size, int (*arr)[size])
{
for(int i=0;i<2;i++)
for(int j=0;j<5;j++)
printf("HEAP row is %d, value is %d:\n", i, arr[i][j]);
}
void function_C(int **arr)
{
for(int i=0;i<2;i++)
for(int j=0;j<5;j++)
printf("HEAP row is %d, value is %d:\n", i, arr[i][j]);
}
int main()
{
function_A(1);
}