我想通过函数创建一个动态的二维数组,但似乎有些东西是非常错误的。当我想把东西放进去时,它会引发一个错误。
错误
0x003a19c8处的未处理异常 p01.exe:0xC0000005:访问冲突 写位置0xcdcdcdcd。
CreateDynamicArray()
short int** CreateDynamicArray(int row, int col)
{
// Creating variable
short int** dynamicArray;
// Creating rows
dynamicArray = (short int**)malloc(row * sizeof(short int*));
// Going trough every row and creating columns for them
for (int i = 0; i < row; i++)
{
dynamicArray[row] = (short int*)malloc(col * sizeof(short int));
}
// Returning created array
return dynamicArray;
}
main()的
// Creating it
dynamicArray = CreateDynamicArray(row, col);
// Filling up with random numbers
for (i = 0; i < row; i++)
{
randomNumber = rand() % 20;
dynamicArray[i][n] = randomNumber; // Here it throws me exception
for (n = 0; n < col; n++)
{
randomNumber = rand() % 20;
dynamicArray[i][n] = randomNumber;
}
}
P.S。 是的,这有点像家庭作业,但我仍然需要帮助这个问题:)
答案 0 :(得分:2)
将行更改为我。
short int** CreateDynamicArray(int row, int col)
{
// Creating variable
short int** dynamicArray;
// Creating rows
dynamicArray = (short int**)malloc(row * sizeof(short int*));
// Going trough every row and creating columns for them
for (int i = 0; i < row; i++)
{
dynamicArray[i] = (short int*)malloc(col * sizeof(short int));
}
// Returning created array
return dynamicArray;
}
答案 1 :(得分:2)
除了Gunner
所说的,n
变量用于循环,但抛出异常的行也使用n
变量。我认为你有一个逻辑错误:)