开发者

initialising 2D 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 initialiser, works fine, even initialises 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, &开发者_C百科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...


The subscript has higher precedence than the dereference operator, so you need a pair of parentheses:

(*inMatrix)[x][y] = z;

However, with your use case, you could just pass the int** directly to fillMatrix; the extra indirection is unnecessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜