Home > database >  Access violation when writing to location inside of 2d array
Access violation when writing to location inside of 2d array

Time:02-28

Hi im doing some assignment that has to do with reading information from a file to write to a 2d int array. When accessing the index of the array to change the data at the point, it throws an exception that says access violation. The arrays has been pre declared in the global scope.

int ImportMapDataFromFile(const char *FileName)
{
    FILE* fp; // file stream
    fopen_s(&fp,FileName, "r"); // opens the file stream according to the file name provided.

    if (fp) {

        fscanf_s(fp, "Width %i\n", &BINARY_MAP_WIDTH); // scans for the width 
        fscanf_s(fp, "Height %i\n", &BINARY_MAP_HEIGHT);// scans for the height

        MapData = new int* [BINARY_MAP_HEIGHT]; // allocates the rows of the map data array
        BinaryCollisionArray = new int* [BINARY_MAP_HEIGHT];// allocates the rows of the binary collision data array
    
        // This for loop initializes and allocates memory for the 
        for (int i{0}; i < BINARY_MAP_HEIGHT; i  )
        {
            MapData[i] = new int[BINARY_MAP_WIDTH]; // allocates the columns of the map data array
            BinaryCollisionArray[i] = new int[BINARY_MAP_WIDTH];// allocates the columns of the binary collision data array
        }

        // Nested for loop to initialize the binary mapping and the collision data
        //from the input file that is provided.
        for (int row{0}; row < BINARY_MAP_HEIGHT; row  )
        {
            for (int col{0}; col < BINARY_MAP_WIDTH; col  )
            {
                int in;
                fscanf_s(fp,"%i", &in);// scans the file for the data for the allocated space in the array
                MapData[col][row] = in; // **access violation happens here**

                (in > 1) ? BinaryCollisionArray[col][row] = 0 : // inputs the binary collision data
                    BinaryCollisionArray[col][row] = in;
            }
        }

        fclose(fp); // close the file stream
        return 1; // returns if successful

    }

    else return 0; // returns if unsuccessful

}

CodePudding user response:

MapData[col][row]

If you go back and review how this matrix was allocated, it looks like the indexes are reversed. The first dimension is the row, the 2nd one is the column. Either that, or change the dimensions' allocations:

MapData = new int* [BINARY_MAP_HEIGHT]; // allocates the rows of the map data array

These look like rows to me, and it's the 1st dimension.

  • Related