C++ 中动态二维数组的访问冲突

access violation with dynamic 2-dimension array in C++

本文关键字:访问冲突 二维数组 动态 C++      更新时间:2023-10-16

感谢您在这里提供帮助
我想将动态二维尺寸作为字符

int n;
char** stars;
int main() {
cin >> n;
for (int i = 0;i < n;i++) {
stars = new char* [n];
stars[i] = new char[n];
for (int j = 0;j < n;j++) {
stars[i][j] = '*';
}
}
for (int i = 0;i < n;i++) {
for (int j = 0;j < n;j++) 
cout << stars[i][j];   //this is where access violation is occured
cout << endl;
}
return 0;
}

而且我还想知道,如果我在这个数组上放 *,那么每次插入时都会在内存(可能是此代码中的堆栈(上生成包含"*"的新 char 数据?

stars = new char* [n];

错误地定位在循环中,因此您为每个字符串重新分配它,并且在新分配的矩阵中仅分配一个字符串。

stars = new char* [n];为什么要在 for 循环中声明这一点? 它将为每个循环一次又一次地分配。 只需在外面声明即可