I am a newbie to C programming (relearning it after a long time) . I am trying to dynamically allocate memory to a 2D array using malloc. I have tried following the answers on stackoverflow like this and this. But I still get the segmentation fault.
My code is as below
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
void allocate2DArray(int **subset, int a, int b)
{
subset = (int **)malloc( a * sizeof(int *));
int i,j;
for(i = 0 ; i < a ; i++)
subset[i] = (int *) malloc( b * sizeof(int));
for(i = 0 ; i < a ; i++)
for(j = 0 ; j < b ; j++)
subset[i][j] = 0;
}
int main()
{
int **subset;
int a = 4, b = 4;
allocate2DArray(subset, a, b);
int i,j;
for( i = 0 ; i < a ; i++)
{
for( j = 0 ; j < b ; j++)
{
printf("%d ", subset[i][j]);
}
printf("\n");
}
}
When I comment the lines to print the array, it doens't give any error and program executes without segmentation fault. Please help me understand where I am going wrong.