0

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;
}
T.Malo
  • 512
  • 1
  • 7
  • 24
  • Even without calling realloc this will crash. Can you please explain again what you want? You want to have a dynamically allocated 2D array, that will grow by one row every time your function is called? – gsamaras Nov 23 '18 at 16:37
  • OK, sorry. What I want is this to create a 2D array. Based on a size. Each time the function is called it will create a array[0][size] then inc the row count by 1 so the next time the function is called it will just create enough memory for that spot than and inc the row again. I will edit the post to make it more clear sorry. – T.Malo Nov 23 '18 at 16:40
  • An array [cannot have zero size](https://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c)! So what do you really want to do? :) – gsamaras Nov 23 '18 at 16:41
  • what do you mean? – T.Malo Nov 23 '18 at 16:52
  • 1
    @T.Malo What do you think `*arr[(*len) - 1]` is like? `(*arr)[(*len) - 1]` or `*(arr[(*len) - 1])`? – chux - Reinstate Monica Nov 23 '18 at 17:05
  • ohh i think i want this (*arr)[(*len) - 1] – T.Malo Nov 23 '18 at 17:13
  • OMG, wait that was my problem... What is this called in C again? dereference and reference of pointers? – T.Malo Nov 23 '18 at 17:19

0 Answers0