C++大型2D数组访问冲突
C++ large 2D Array access violation
所以我创建了一个程序,用于查找最佳二进制搜索树,当数据集大约为100时,它非常有效,但当我尝试使用大于1000的数据集时,当weight[I][I]=frequency[I]时,我会遇到访问违规;在computeOBST函数内部调用。我不确定这个数据集是很大还是什么。我被卡住了,不确定还能做些什么来尝试任何帮助都会很好。
int* keys = new int[numKeys];
int* keyLevel = new int[numKeys];
int* frequency = new int[numKeys];
int** weight = new int*[numKeys+2];
int** cost = new int*[numKeys];
int** root = new int*[numKeys];
void allocateArraySpace(int n){
int i;
// Allocate space for the 2-dim'l cost array
for (i = 0; i < numKeys + 2; i++) {
cost[i] = new int[numKeys + 2];
}
for (i = 0; i < numKeys + 1; i++) {
keyLevel[i] = numKeys + 1;
}
// Allocate space for the 2-dim'l root array
for (i = 0; i < numKeys + 1; i++) {
root[i] = new int[numKeys + 1];
}
//Allocate space for the 2-dim'l weight array
for (i = 0; i <= numKeys + 2; i++) {
weight[i] = new int[numKeys + 2];
}
}
void computeOBST(int n) {
numKeys = n;
int i, j, k, h, m;
allocateArraySpace(numKeys);
//creating weight matrix
for (int i = 1; i <= numKeys + 1; i++)
{
weight[i][i] = frequency[i];
for (j = i + 1; j <= numKeys; j++)
weight[i][j] = weight[i][j - 1] + frequency[j];
}
//
for (i = 1; i <= numKeys; i++)
for (j = i + 1; j <= numKeys + 1; j++)
cost[i][j] = INT_MAX;
//
for (i = 1; i <= numKeys + 1; i++)
cost[i][i - 1] = 0;
//
for (i = 1; i <= numKeys; i++) {
cost[i][i] = weight[i][i];
root[i][i] = i;
}
cost
的大小只有numKeys
,但在allocateArraySpace
中的循环中,您访问它的numKeys+2
元素吗?其他阵列也存在类似的问题。
请记住,C++中的数组是基于0的,所以如果执行cost = new int *[numKeys]
,那么cost[numKeys-1]
是可以的,但cost[numKeys]
和cost[numKeys+1]
是越界的。
int* frequency = new int[numKeys]
然后
for (int i = 1; i <= numKeys + 1; i++) { weight[i][i] = frequency[i]; ...
你会出界的未定义的行为。碰巧,小值的UB不会导致分割错误,而numKeys
的高值则会导致分割错误。
这只是一个例子,你在很多地方都有同样的错误。再次检查所有循环和数组边界,并设置正确的限制。
通常,当您跨越大小为numKeys
的阵列时,您可以按以下方式扫描它(请记住,C阵列是基于零的):
for (int i = 0; i < numKeys; i++) // first index is 0, last is numKeys-1
相关文章:
- 按字符值访问int数组
- C++ - 循环访问指针数组会导致错误
- 通过unique_ptr访问std::数组
- 为什么我无法访问指向数组中成员函数的指针?
- 在函数 strcpy() 中访问字符数组时出现分段错误
- 在 C++ 中访问 JSON 数组值
- 在C++中访问结构数组中的数据
- C++:在多个线程中访问同一数组/向量的不同单元格是否会产生数据竞赛?
- 是否可以使用宏来访问动态数组或向量中的元素或为其赋值
- 从类访问char数组
- 更快地访问 C++ 数组中的随机元素
- 如何修复访问动态数组中结构中的字符串变量时"segmentation fault (core dumped)"错误
- 在C++中使用 RapidJSON 访问 JSON 数组的字段
- 创建 2D 数组类:如何访问 2D 数组类(如 array[x][y))中的元素
- 通过矢量下标访问 Fortran 数组,相当于 cpp
- 在能够从 Web 浏览器访问大型数组数据的同时存储它的最可行方法是什么?
- 有没有办法使用初始化到第一行的指针访问 2d 数组的第二行?
- 通过C++中的指针访问字符数组
- C++ 如何使用类方法正确访问动态数组元素
- 访问 2D 数组时的读取冲突