提问者:小点点

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


感谢您在此提供帮助
我希望将动态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数据就会在内存中生成(在这段代码中可能是堆栈)?


共2个答案

匿名用户

        stars = new char* [n];

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

匿名用户

stars=new char*[n];为什么要在for循环中声明它? 它将一次又一次地为每个循环分配。 到外面去申报就行了

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|动态|二维|数组|访问|冲突)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?