Problem intialising 2D array
Posted
by TeeJay
on Stack Overflow
See other posts from Stack Overflow
or by TeeJay
Published on 2010-05-07T02:13:44Z
Indexed on
2010/05/07
2:18 UTC
Read the original article
Hit count: 188
c
|multidimensional-array
Ok, so I have a 2D Array that is initialised with values from a file (format: x y z).
My file reads in the values correctly but when adding the z value to the matrix/2DArray, I run into a segfault and I have no idea why. It is possibly incorrect use of pointers? I still don't quite have the hang of them yet.
This is my intialiser, works fine, even intialises all "z" values to 0.
int** make2DArray(int rows, int columns)
{
int** newArray;
newArray = (int**)malloc(rows*sizeof(int*));
if (newArray == NULL)
{
printf("out of memory for newArray.\n");
}
for (int i = 0; i < rows; i++)
{
newArray[i] = (int*)malloc(columns*sizeof(int));
if (newArray[i] == NULL)
{
printf("out of memory for newArray[%d].\n", i);
}
}
//intialise all values to 0
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
newArray[i][j] = 0;
}
}
return newArray;
}
This is how I call the initialiser (and problem function).
int** map = make2DArray(rows, columns);
fillMatrix(&map, mapFile);
And this is the problem code.
void fillMatrix(int*** inMatrix, FILE* inFile)
{
int x, y, z;
char line[100];
while(fgets(line, sizeof(line), inFile) != NULL)
{
sscanf(line, "%d %d %d", &x, &y, &z);
*inMatrix[x][y] = z;
}
}
From what I can gather through the use of ddd, the problem comes when y gets to 47.
The map file has a max "x" value of 47 and a max "y" value of 63, I'm pretty sure I haven't got the order mixed up, so I don't know why the program is segfault-ing? I'm sure it's some newbie mistake...
© Stack Overflow or respective owner