6

I'm working on a program using arrays and I'm trying to figure out

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};

Could someone please explain this for me.

2
  • 1
    All unset values are set to 0 in this case. Commented Dec 2, 2014 at 11:39
  • Try it. Three lines of code... Commented Dec 2, 2014 at 15:01

2 Answers 2

6
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 one is similar. You know the answer.

Sign up to request clarification or add additional context in comments.

4 Comments

I got that part, they only thing I wasn't sure about is identifying the value.
@michaelm If you got this part, the rest is easy, the only thing I think worth mentioning is indexing starts from 0.
So since I have a 2D array (a row/column grid), but only specified the first line, so the rest get initialized to zero so I should expect the code to write zero right?
@michaelm As long as there's an initializer, all the elements not explicitly initialized are initialized to 0. For instance, int scores[3][3] = {} sets all elements to 0.
3

Array indexing is zero-based.

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

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

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

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

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

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

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

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

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

  • foo[0][0] is 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

1 Comment

@michaelm Don't forget to accept either Yu Hao's answer or my answer if one of them answered your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.