简体   繁体   中英

Access diagonal elements in a 2D array stored in a 1D array

Suppose my 2D array is:

int a[4][4] = {
               1,0,0,0,
               0,1,0,0,
               0,0,1,0,
               0,0,0,1
              };

Suppose its stored in a 1D array as:

int b[16]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};

In general, assume a is of size mxn and b is of size mn . Using a single for loop I want to be able to access all the diagonal elements, ie output should be 1 1 1 1.

I understand A[i][j] = B[i*n+j]; but if I'm only using a single for loop, I don't have a j index .

Any help would be highly appreciated.

Edit:

Note let m=n be for all practical purposes. The interface I'm using expects two separate variables for row and column size. But I'm only working with square matrices.

If you know your 2D array is a perfect square (ie exactly as many rows as columns), you don't need a j index:

As a 2D array:

for(i = 0; i < height; i++)
{
    printf("%d\n", array[i][i];
}

As a 1D array:

for(i = 0; i < height; i++)
{
    printf("%d\n", array[i*height+i]);
}

It's simple to it for a 2-d array.

for(int i=0; i<4; i++)
   printf("%d", a[i][i]);

And for a single dimension array, it is not difficult either.

for(int i=0; i<16; i=i+5)
   printf("%d", b[i]);

You only needto consider the number of columns.

#define COLUMNS 4
#define ROWS 4

b[16]={1,0,0,0,
       0,1,0,0,
       0,0,1,0,
       0,0,0,1};

int i = 0;
for(; i < ROWS; i++ ){
  printf("%d\t",b[COLUMNS*i+i]);
}

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