Ashwin
Ashwin

Reputation: 431

Array 2D to 1D conversion and confusion

I am confused to convert a 2D array into 1D array. I want to write a neighboring 8 elements for "a11" (which is at (1,1)) in the form of width ,rows and cols format without using for loop.

       |<--Width--->|
            cols
        ____________
       | a00 a01 a02 
  rows | a10 a11 a12 
       | a20 a21 a22 

I tried in this way :

a00 = pSrc[(cols-1)+ (rows - 1)*width];                                           
a02 = pSrc[(cols-1)+ (rows  + 1)*width];                                           
a10 = pSrc[cols+ (rows -1)*width];                                                 
a12 = pSrc[cols+ (rows +1)*width];                                                 
a20 = pSrc[(cols+1)+ (rows  - 1)*width];                                           
a22 = pSrc[(cols+1)+ (rows  + 1)*width];                                           
a01 = pSrc[(cols-1)+ (rows )*width];                                               
a21 = pSrc[(cols+1)+ (rows )*width];                                               

But I think I did some mistake .Can any one help me in that .

Upvotes: 2

Views: 96

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753805

It isn't clear how pSrc is defined since you don't show its definition. However, your code is consistent with it being declared as a 1D array:

int pSrc[9];   // Or a larger dimension

Your code can sensibly be written so it is more uniformly laid out:

a00 = pSrc[(cols-1) + (rows-1)*width];
a01 = pSrc[(cols-1) + (rows+0)*width];
a02 = pSrc[(cols-1) + (rows+1)*width];
a10 = pSrc[(cols+0) + (rows-1)*width];
a12 = pSrc[(cols+0) + (rows+1)*width];
a20 = pSrc[(cols+1) + (rows-1)*width];
a21 = pSrc[(cols+1) + (rows+0)*width];
a22 = pSrc[(cols+1) + (rows+1)*width];

The +0 will be ignored by even the most simple-minded compiler, almost certainly without even turning the optimizer on, but it makes the code much easier to read. I also resequenced the entries so the row above are listed first, then the row in the middle, and then the bottom row. Again, it makes it easier to see the patterns.

It is then clear that you are using 'rows' and 'cols' backwards. You actually need:

a00 = pSrc[(cols-1) + (rows-1)*width];
a01 = pSrc[(cols+0) + (rows-1)*width];
a02 = pSrc[(cols+1) + (rows-1)*width];
a10 = pSrc[(cols-1) + (rows+0)*width];
a12 = pSrc[(cols+1) + (rows+0)*width];
a20 = pSrc[(cols-1) + (rows+1)*width];
a21 = pSrc[(cols+0) + (rows+1)*width];
a22 = pSrc[(cols+1) + (rows+1)*width];

Upvotes: 2

Related Questions