感谢您在此提供帮助
我希望将动态2D维度作为字符
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循环中声明它? 它将一次又一次地为每个循环分配。 到外面去申报就行了