我创建了一个动态分配的2d数组,当我尝试将其删除时,根据该数组的尺寸会出现错误。
如果行多于列,则没有问题:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int num_rows = 8;
int num_cols = 6;
char **charBoard = new char*[num_rows+1];
for(int i = 0; i<=num_cols; i++){
charBoard[i] = new char[num_cols+1];
}
for (int i = 0; i <=num_rows; i++){
delete[] charBoard[i];
}
//free the main array
delete[] charBoard;
return 0;
}
如果列多于行,则会出现错误:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int num_rows = 4;
int num_cols = 6;
char **charBoard = new char*[num_rows+1];
for(int i = 0; i<=num_cols; i++){
charBoard[i] = new char[num_cols+1];
}
for (int i = 0; i <=num_rows; i++){
delete[] charBoard[i];
}
//free the main array
delete[] charBoard;
return 0;
}
然后我得到这个错误: 中止(核心已弃用)
我不知道为什么。我是否删除了不正确的内容?
答案 0 :(得分:1)
填充数组时,您在变量名称上输入了错误:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int num_rows = 4;
int num_cols = 6;
char **charBoard = new char*[num_rows+1];
for(int i = 0; i <= num_cols; i++) {
^^^^^^^^^
charBoard[i] = new char[num_cols+1];
}
for (int i = 0; i <= num_rows; i++) {
^^^^^^^^^
delete[] charBoard[i];
}
//free the main array
delete[] charBoard;
return 0;
}
这是该代码的更正版本:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int num_rows = 4;
int num_cols = 6;
char **charBoard = new char*[num_rows+1];
for(int i = 0; i <= num_rows; i++) {
charBoard[i] = new char[num_cols+1];
}
for (int i = 0; i <= num_rows; i++) {
delete[] charBoard[i];
}
//free the main array
delete[] charBoard;
return 0;
}