2D array initialization

Ok, so I have a 2D array that is initialized with values ​​from a file (format: xyz).
My file reads the values ​​correctly, but when adding the z value to the / 2DArray matrix, I run into a segfault and I have no idea why. Possibly misuse of pointers? I still don't quite understand them.

This is my initializer, works great, even initializes 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 initializer (and the 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 compile with ddd, the problem occurs when y reaches 47.
The map file has a maximum "x" value of 47 and a maximum "y" value of 63, I'm sure I have no confusion so I don't know why is the program segfault-ing? I'm pretty sure this is a beginner's mistake ...

+2


a source to share


1 answer


Subscript takes precedence over the dereference operator, so you need a pair of parentheses:

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

      



However, using your use case, you can simply pass int**

directly to fillMatrix

; no additional redirection is required.

+3


a source







All Articles