Two-dimensional array initialization values

I am working on a program using arrays and I am trying to understand

First, with the following array declaration, what is the value stored in the scores[2][2] element?

 int scores[3][3] = { {1, 2, 3} }; 

And also with this array declaration, what is the value stored in the scores[2][3] element?

 int scores[5][5] = {5}; 

Can anyone explain this to me.

+5
source share
2 answers

Array indexing is based on zero.

This means that for: int foo[3] = {10, 20, 30};

  • foo[0] - 10
  • foo[1] - 20
  • foo[2] - 30

For multidimensional arrays, you should think of them as arrays of arrays.

So, this will create an array containing two int[3] s: int foo[2][3] = {{10, 20, 30}, {40, 50, 60}};

  • foo[0][0] - 10
  • foo[0][1] - 20
  • foo[0][2] - 30
  • foo[1][0] - 40
  • foo[1][1] - 50
  • foo[1][2] - 60

C supports partial initialization. In which it will default to all non-initialized values ​​equal to 0.

So, if you must do this: int foo[3] = {5};

  • foo[0] - 5
  • foo[1] is 0
  • foo[2] is 0

Similarly for a multidimensional array: int foo[2][3] = {5};

  • foo[0][0] - 5
  • foo[0][1] is 0
  • foo[0][2] is 0
  • foo[1][0] is 0
  • foo[1][1] is 0
  • foo[1][2] is 0
+3
source
 int scores[3][3] = { {1, 2, 3} }; 

is equivalent to:

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

The other is similar. You know the answer.

+5
source

Source: https://habr.com/ru/post/1208137/


All Articles