嗨,我正在做一些與從檔案中讀取資訊以寫入 2d int 陣列有關的任務。當訪問陣列的索引以更改該點的資料時,它會拋出一個例外,表示訪問沖突。陣列已在全域范圍內預先宣告。
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
}
uj5u.com熱心網友回復:
MapData[col][row]
如果您回傳并查看該矩陣是如何分配的,看起來索引是顛倒的。第一個維度是行,第二個維度是列。要么,要么改變維度的分配:
MapData = new int* [BINARY_MAP_HEIGHT]; // allocates the rows of the map data array
這些對我來說看起來像行,它是第一個維度。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/434361.html
上一篇:C中結構中的元素數
下一篇:重復洗掉最大平均子陣列
