-3
struct Point
{
    double x,y;
};
Point p;
struct Disk
{
    Point center;
    int radius;
};
Disk d;
int main()
{  
   d.center.x=1.2;
   cout<<p.x;
}

Could someone please explain me the output of this code? why am I not getting the value of x as 1.2 and 0 instead?

  • 2
    `p` and `d` are completely unrelated objects. I don't know why you expect setting a value inside one to be reflected when reading from the other... Are you learning from a [good book](https://stackoverflow.com/q/388242/1171191)? – BoBTFish Mar 04 '18 at 09:09
  • Thankyou, I am a newbie could you suggest me the resources and other materials for learning. – Monash Chhetri Mar 04 '18 at 11:01
  • Take a look at [this](https://stackoverflow.com/q/388242/9254539). – eesiraed Mar 04 '18 at 18:59

1 Answers1

0

Let's go through your code line by line.

First, you created a Point called p. So p is sitting in the memory somewhere:

Memory:  p:[x, y]

Then, you created a Disk called d, which stores it's own Point object inside it.

Memory:  p:[x, y]                     d:[center:[x, y], radius]

These are completely separate objects. When you modify the Point stored in d with d.center.x=1.2, it does not affect p at all.

Therefore, p is uninitialized, and reading the value of uninitialized variables causes undefined behavior, meaning anything can happen, in this case usually getting a random value.

eesiraed
  • 4,626
  • 4
  • 16
  • 34