简体   繁体   中英

c++ error in 2D array index

I am working on a C++ program and the issue is in the below code. (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

    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 . but An error keeps coming up at array[k-rows][l]=Array2[k][l]; which says Thread 1:Exc_BAD_ACCESS(code = 1, address = 0xe) . (i am using xcode 7.2)

With rows= 5/2 ; you set rows to 2 . Than you allocate 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] . You never allocated row with index 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 )
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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