写入动态二维数组时出现访问冲突...有时

发布于 2024-08-28 11:14:03 字数 558 浏览 4 评论 0原文

该程序旨在生成动态数组,但是在给定某些维度时写入时会出现访问冲突错误。例如:R = 6,C = 5 崩溃,但 R = 5,C = 6 则不会。如果您想知道,“修复”这个损坏的程序不是我的作业,这是我们在课堂上教的方法。我的评估的一部分也是使用这种方法,所以向量已经被淘汰了。提前致谢!

#include <iostream>

using namespace std;

int main(){

const int R = 6;
const int C = 5;

char **d;

d = new char *[R];

for(int i=0; i<C; ++i){
    d[i] = new char[C];
}

//initialise
for(int i=0; i<R; ++i){
    for(int j=0; j<C; ++j){
        d[i][j] = 'd';
        cout<<d[i][j];
    }
    cout<<endl;
}
cout<<endl;

system("pause");
return 0;
}

This program is meant to generate a dynamic array, however it gives an access violation error when writing when given certain dimensions. Eg: R = 6, C = 5 crashes, but then R = 5, C = 6 doesn't. In case your wondering, it isn't my homework to "fix" this broken program, this is the method we were taught in class. Also part of my assessment is to use this method, so vectors are out. Thanks in advance!

#include <iostream>

using namespace std;

int main(){

const int R = 6;
const int C = 5;

char **d;

d = new char *[R];

for(int i=0; i<C; ++i){
    d[i] = new char[C];
}

//initialise
for(int i=0; i<R; ++i){
    for(int j=0; j<C; ++j){
        d[i][j] = 'd';
        cout<<d[i][j];
    }
    cout<<endl;
}
cout<<endl;

system("pause");
return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

筱果果 2024-09-04 11:14:03
for(int i=0; i<C; ++i){
    d[i] = new char[C];
}

应该是

for(int i=0; i<R; ++i){
    d[i] = new char[C];
}
for(int i=0; i<C; ++i){
    d[i] = new char[C];
}

should be

for(int i=0; i<R; ++i){
    d[i] = new char[C];
}
七七 2024-09-04 11:14:03

您的第一个循环为 0C-1 之间的 d 数组的元素创建一个新的 char 数组。

第二个外循环从 0R-1(包含)。所以最后访问的d[i]没有被初始化。这通常会失败。

要解决该问题,请将其用作您的第一个循环

for(int i=0; i<R; ++i){
    d[i] = new char[C];
}

Your first loop creates a new char array for elements of the d array between 0 and C-1 inclusively.

The second outer loop goes from 0 to R-1 inclusively. So the last d[i] accessed is not initialized. This will typically fail.

To solve the problem, use that as your first loop

for(int i=0; i<R; ++i){
    d[i] = new char[C];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文