I am working on a function that internalizes and extends a 2D array by reference. Basically, when I call this function I want grow the row by 1 and create a size of columns each time.
(EDIT: for clarification)
2D array **foo = NULL
call func_v2()
if **foo = NULL
then foo = [0]
then foo = [0][size]
then foo = [1]
call func_v2()
**foo != NULL
foo[1][size]
foo[2]
call func_v2()
**foo != NULL
foo[2][size]
foo[3]
//And so on and so on
The idea is that each time time I call this function I am setting up the next row so that I can allocate space for column when I call the function again.
My problem is every time I call realloc in my function it crashes. I am not sure why realloc does not work here. How can I get realloc to work and can someone explain why it doesn't work thanks.
void func_v2(int ***arr, int size, int *len){
/*set up first row space if NULL*/
if (*arr == NULL) {
*arr = malloc((*len) *sizeof(int*));
}
/*create columns in the array*/
(*arr)[(*len) - 1] = malloc(size * sizeof(int *));
/*debug test set with values*/
for (int j = 0; j < size; j++) {
(*arr)[*len - 1][j] = (*len);
}
/*increment length of row*/
++(*len);
/*extend row size*/
*arr = realloc(*arr, ((*len)) * sizeof(int*)); //WHY DOES THIS NOT WORK?
}
int main(void) {
int **foo = NULL;
int size = 5;
int len = 1;
func_v2(&foo,size,&len);
for (int i = 0; i < len-1; i++) {
for (int j = 0; j < size; j++) {
printf("%d ", foo[i][j]);
}
printf("\n");
}
return 0;
}