3
int eye[3][3] = {
  { 1,0,0 },
  { 0,1,0 },
  { 0,0,1 }
};

Is there a shorter way to initialize it? It's so regular that there must be a smarter way to initialize it, especially if it's more than 3x3, say 10x10 or more.

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
Joshua MN
  • 1,486
  • 2
  • 13
  • 26
  • Take a look at this fine answer http://stackoverflow.com/questions/201101/how-to-initialize-an-array-in-c – Mikkel Nielsen May 13 '13 at 18:46
  • Initialize to all zeros with `eye[3][3] = { {0 } }` and then loop throught the diagonal and set it to one. – Carsten May 13 '13 at 18:46
  • 3
    There are lot of materials on this theme. Your "eye-matrix" also calls **identity matrix**. It is better to search "identity matrix" rather "eye-matrix". – NG_ May 13 '13 at 18:53

4 Answers4

9

In you can write:

int eye[][3] = { [0][0] = 1, [1][1] = 1, [2][2] = 1 };

all other elements are zeroed, moreover the compiler figures out the size of the array for you. Just don't skip the second size (3).

Btw. in your code you don't have to use the double braces, this would be fine too:

int eye[3][3] = {
  1,0,0,
  0,1,0,
  1,0,1,
};

In you can also leave the trailing comma, just for symmetry and future refactorings

Other solutions probably require you to write some code, which may indeed save you some time/space in file. But note that this way you're splitting declaration and "initialization", which in case of e.g. globals can make a difference.

emesx
  • 12,555
  • 10
  • 58
  • 91
6

You can use designated initializers:

int eye[3][3] = { [0][0]=1, [1][1]=1, [2][2]=1};

All the other elements will be initialized to 0 as per C standard's guarantee.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • 1
    If N=1000, we need to write 1000 designated initializer entries manually? Is it possible to simplify? – taocp May 13 '13 at 18:50
  • 1
    Well, you have to make a concession at some point. Looping is an obvious solution for very large arrays. This allows initializing random elements of array with any value. – P.P May 13 '13 at 18:53
4

You may try the following:

#define SIZE 3
int eye[SIZE][SIZE] = {0};

for (int i = 0; i < SIZE ; ++i)
{
  eye[i][i] = 1;
}
taocp
  • 23,276
  • 10
  • 49
  • 62
1

If you want to store {{ 1,0,0 }, { 0,1,0 }, ...} this style of values in square matrix means, you can write a simple logic as below.

#define SIZE 3
int eye[SIZE][SIZE] = {0};
int *p = (int *)eye;

for (i = 0; i < (SIZE * SIZE); i = i + (SIZE + 1))
{
    p[i] = 1;   
}

or

for (i = 0; i < SIZE; i++)
{
    for (j = 0; j < SIZE; j++)
    {
        if (i == j)
        {
            eye[i][j] = 1;          
        }
        else
        {
            eye[i][j] = 0;
        }
    }
}

Note : Above logic is only for the sample value you have given. So try to find similar logic if your values are having some relation. If not so, then no other way to initialize it directly even if size of matrix is 1000x1000.

rashok
  • 12,790
  • 16
  • 88
  • 100