-10
struct myclass {
    int id;
    myclass(): id(-1){};
};

myclass *a;
cout >> a->id;

This above is a demonstration of my long program. The output should be -1. But I do not know why the output becomes -842150451.

Boann
  • 47,128
  • 13
  • 114
  • 141
Taitai
  • 444
  • 1
  • 6
  • 16

1 Answers1

8

You have Undefined Behavior!

You create a myclass pointer, but never point it to anything. And then you try to dereference the dangling or wild pointer.

Try this instead to get the -1 you're expecting:

myclass a;
std::cout << a.id;
scohe001
  • 14,655
  • 2
  • 30
  • 50