There are multiple issues with your code. Here are solutions to your issues in your program.
First, you need to allocate space for C
array. This is already been covered by tacp and hence, I am skipping the same.
The main issue is coming from init(A,B)
function. There are couple of issues here. One, A
and B
are global pointers and hence, this is really not required to be passed as a function argument. However, since your code is designed for the same, you would have to incorporate the following changes
//main function invoking init
init(&A, &B); // Pass references to A and B
The foot print of init
needs to be modified as
void init(int ***Aptr, int ***Bptr)
{
int **A; // Define a local pointer to keep rest of the code intact
int **B; // Define a local pointer to keep rest of the code intact
.....................
//Rest of your code
// End of function
*Aptr = A;
*Bptr = B;
}
With these 2 changes, your code should be ready to work fine. In your earlier implementation, only the local copy of A
and B
were updated in the init
function and it wasn't reflected on the actual pointers. Hence, when init
completed, A
and B
were pointing to potentially NULL
pointers which was the cause of the segmentation fault.
There is another solution to this problem. You could avoid passing the arguments to init
i.e. convert init
to init()
and modify the implementation as void init()
. This would work fine (again assuming C
is also allocated)
However, there is still one more point. Lastly, you would require to take care to delete the memory for C
array also (assuming it is allocated in init
function) as
for(i = 0; i < SIZE; i++)
free((void *)C[i]);
free((void *)C);
Postscript:
From a programming perspective, I feel you shouldn't mix global variables and passing these very global variables as function parameters. The scope is global which means the function can definitely access the variables and hence, don't require the same to be passed to the function.