简体   繁体   English

2D数组索引中的C ++错误

[英]c++ error in 2D array index

I am working on a C++ program and the issue is in the below code. 我正在使用C ++程序,问题在下面的代码中。 (NB: code has been simplified for readability but the essence is still there). (注意:代码已经过简化,以提高可读性,但本质仍然存在)。 In the first part i am just creating a 2D array with a few simple conditions 在第一部分中,我只是创建一些简单条件的2D数组

    rows= 5/2;
    cols= 4/2;

    char** array;
    if(rows%2 !=0 ){
     array = new char*[rows+1];
    }else {
         array = new char*[rows];
    }
    for(int k = 0; k < rows; k++)
    {
        if(columns%2 !=0){
            array[k] = new char[cols+1];
        }else{
            array[k] = new char[cols];
        }

    }

So far so good. 到现在为止还挺好。 the code works perfectly. 该代码运行完美。 the next part is where the issue is, 下一部分是问题所在

  for(int k = rows; k<5; k++){
        for (int l=0; l< 2; l++){
            array[k-rows][l]=Array2[k][l];            
        }
    }

so basically this code is just retrieving a small part of a larger array ( array2 ) and inserting it into array . 因此,基本上,这段代码只是检索较大数组( array2 )的一小部分并将其插入到array but An error keeps coming up at array[k-rows][l]=Array2[k][l]; 但是错误不断出现在array[k-rows][l]=Array2[k][l]; which says Thread 1:Exc_BAD_ACCESS(code = 1, address = 0xe) . 它说Thread 1:Exc_BAD_ACCESS(code = 1, address = 0xe) (i am using xcode 7.2) (我正在使用xcode 7.2)

With rows= 5/2 ; rows= 5/2 ; you set rows to 2 . 您将rows设置为2 Than you allocate 2 rows array = new char*[rows]; 比您分配2 rows array = new char*[rows]; . But you iterate from 2 to 4 for(int k = rows; k<5; k++) and write to rows 0 to 2 array[k-rows][l] . 但是, for(int k = rows; k<5; k++) ,您需要从2迭代到4 for(int k = rows; k<5; k++)然后写入0到2行array[k-rows][l] You never allocated row with index 2. 您从未分配带有索引2的行。

rows= 5/2; // now rows is 2
...
if(rows%2 !=0 ) // 2%2!=0

Try this: 尝试这个:

rows= 5;
cols= 4;

int allocRows = ( rows%2==0 ) ? rows/2 : rows/2+1;
rows=rows/2;

int allocCols = ( cols%2==0 ) ? cols/2 : cols/2+1;
cols=cols/2;

array = new char*[allocRows];
for(int k = 0; k < allocRows; k++)
    array[k] = new char[allocCols];

... or this ... ... 或这个 ...

int origRows = rows; 
rows= 5/2;
...
if(origRows%2 !=0 )
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM