0

I have created a double int pointer in main and called a function where I allocate place for this pointer.

void foo(int **array)
{
    int i, j;
    array = (int **)malloc(sizeof(int *)*(100)); //rows

    for(i=0; i<100; i++)
        array[i] = (int *)malloc(sizeof(int)*(50)); //cols

    array[0][0] = 10;
}

and in main I have just these lines;

int** array;

foo(array);

printf("%d \n", array[0][0]);

As a result I get a segmentation fault. Since I am passing a pointer and it is allocated in foo method, does it mean that in main method it is not allocated? How can I solve it without making foo function to return a double pointer?

user3764893
  • 697
  • 5
  • 16
  • 33

2 Answers2

2

The way your function is defined:

void foo(int **array);

the two-dimensional array is a local variable that goes out of scope at the end of the function. You will lose the allocated memory and your main function won't know about the allocated memory, because the array in foo and main are different.

One solution is to create an int ** in main and then pass a pointer to that in foo:

void foo(int ***array);

You can then update the local variable in main via the pointer passed to foo, *array;

Another solution is to return the freshly allocated memory from the function:

int **foo(void);

This is a frequent question here and there should be plenty of code examples for array allocation.

M Oehm
  • 28,726
  • 3
  • 31
  • 42
0

finally, check this. update your foo function as below and it should work as per your expectations,

void foo(int (***array))
{
    int i;

     *array = (int **) malloc(100*sizeof(int *)); //rows

    for(i=0; i<100; i++){
        (*array)[i] = malloc(50*sizeof(int));} //cols

    *array[0][0] =10;
}

In the main function, pass the address of array variable.

foo(&array);

hope this helps!

sameera sy
  • 1,708
  • 13
  • 19