I've made a program that creates a 2D array in main
, and passes the array to be populated. I'd like to create the array in a function for modularity and to keep main
clean, s cut down version of my original code so far are:
int main(int argc, char *argv[])
{
long iWidth; /*Image width*/
long **arr; /*creating array to hold the black and white image*/
<get width of a square image into iWidth>
arr = mallocSafe(iWidth * sizeof *arr); /*Can dynamically allocate memory for the 3d array now width is known*/
for (i=0; i < iWidth; i++) /*allocate the array (rows)*/
{
arr[i] = mallocSafe(iWidth * sizeof *arr[i]); /*allocate the array (columns)*/
}
buildArr(iWidth, arr);
...
}
buildArr(iWidth, arr)
{
...
for (x = 0; x < iWidth; x++) /*fills the array with white pixels*/
{
for (y = 0; y < iWidth; y++)
{
arr[x][y] = 0;
}
}
}
This works fine, but when I malloc and initialise the array in a separate function I get a segfault when I try to populate the array in the buildArray function. Clearly I don't understand arrays as well as I thought. Could someone point out where I'm going wrong? I've tried a few different ways, the latest is as follows:
int main(int argc, char *argv[])
{
long iWidth; /*Image width*/
long **arr /*creating array to hold the black and white image*/
createArray(arr, iWidth);
buildArr(iWidth, arr)
}
void createArray(long** arr, long size)
{
int i;
arr = mallocSafe(size * sizeof *arr); /*Can dynamically allocate memory for the 3d array now width is known*/
for (i=0; i < size; i++) /*allocate the array (rows)*/
{
arr[i] = mallocSafe(size * sizeof *arr[i]); /*allocate the array (columns)*/
}
}
buildArr(iWidth, arr)
{
...
for (x = 0; x < iWidth; x++) /*fills the array with white pixels*/
{
for (y = 0; y < iWidth; y++)
{
arr[x][y] = 0;
}
}
}
Hopefully I've not made any errors in trying to make my code simpler to read!