Structure program

Hello -

I am new here and am stumped as to why this snippet yields 34.
Can anyone shed some light on this for me?

struct sct {
int t[2];
};

struct str {
sct t[2];
};

int main() {
str t[2] = { {0, 2, 4, 6}, {1, 3, 5, 7} };
cout << t[1].t[0].t[1] << t[0].t[1].t[0];
return 0;
}

Isn't it lovely how similar looking names make code harder to read?
Lets rename some:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

struct sct {
  int foo[2];
};

struct str {
  sct bar[2];
};

int main() {
  str gaz[2] = { {0, 2, 4, 6}, {1, 3, 5, 7} };
  std::cout << gaz[1].bar[0].foo[1];
  std::cout << gaz[0].bar[1].foo[0];
  return 0;
}

Which one is your primary question:
* Where does the number come from?
or
* How did it get there in the first place?
Hi -

I guess my question is how does this produce an output of 34.

Thank you
Last edited on
There are two values that are written to std::cout. The first happens to be 3 and the second 4, and that is why you see 34.

The gaz is an array. Therefore, the gaz[1] is an array element. The elements of gaz have type str.

The bar is a member of an str element. The bar is an array. bar[0] is an element in bar.

In other words: gaz[1].bar[0] is the first element of member array bar in the second str object element within array gaz.

The type of bar's elements is sct. The sct objects have a member foo that is an array of integers.

Do you now start to see where the values come from?
Actually yes - I think I understand it now.

In my own terms: gaz[1] is {1, 3, 5, 7} ,
.bar[0] is {1, 3] and the
.foo[1] = 3

Sort of like process of elimination
Topic archived. No new replies allowed.