Dynamic Memory Allocation (Seg. Fault)
Hi everyone, first time user here. I just want to know if anyone can help me with a very simple piece of code.
In a nutshell, I would like to dynamically allocate memory for a 2D array using new and delete. (I know I know, it is a common question but please keep reading). Instead of dynamically allocating the memory in the main() function, I would like to pass the 2D array to a function called "initArray(int *array[], int *numrows, int *numcols)". Once I initialize the array, I return back to the main () function and print a random value, say cout << array[1][1] << endl;. However, I received a segmentation fault which did not make any sense.
Below is the entire code of my program:
Code:
#include <iostream>
using namespace std;
//Function Prototype
void initArray (int *array[], int *numrows, int *numcols);
//Main Function
int main ()
{
int **a;
int numrows = 5, numcols =5;
//Pass the double pointer "a" along with the addresses of numrows and numcols
initArray (a, &numrows, &numcols);
//when returning from function initArray(), print out element at row 1, column 1
cout << a[1][1] << endl;
return (0);
}
void initArray (int *array[], int *numrows, int *numcols)
{
int i, j;
array = new int* [*numrows];
for (i = 0; i < *numrows; i++)
{
array[i] = new int [*numcols];
}
for (i = 0; i < *numrows; i++)
{
for (j = 0; j < *numcols; j++)
array[i][j] = i*j;
}
//print the element at row 1 and column 1
cout << array[1][1] << endl;
}
For some strange reason, the cout statement in my initArray function prints normally whereas the same cout statement back in my main() function, it yells at me that I have a segmentation fault.
If my logic is correct, I would assume that passing double pointer "a" essentially passes the address of where the double pointer is located in memory. My initArray function receives the address (int *array[] parameter), it should start initializing the matrix with the values i*j and writes it in memory. What I don't understand that why is the cout function does not cause a segmentation fault in the initArray function but occurs in my main() function.
Would someone please give me a solution or an explanation to this?
Thanks and with sincerest regards