开发者

Access Violation When Writing Dynamic 2D Array... Sometimes

开发者 https://www.devze.com 2022-12-26 05:16 出处:网络
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 = 开发者_如何学JAVA5 crashes, but then R = 5, C =

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 = 开发者_如何学JAVA5 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;
}


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];
}


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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消