-7

I have some code taken as examples to pointer.

short value=7;

short *ptr=&value;

std::cout<<&value<<'\n';
std::cout<<value<<'\n';
std::cout<<ptr<<'\n';
std::cout<<*ptr<<'\n';
std::cout<<'\n';

*ptr=9;

std::cout<<&value<<'\n';
std::cout<<value<<'\n';
std::cout<<ptr<<'\n';
std::cout<<*ptr<<'\n';
std::cout<<'\n';

I wonder when I change *ptr to 9, why does the value of "value" change according to *ptr?

  • 13
    This is how pointers work. When you dereference them you have the object the pointer points to. Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Apr 02 '18 at 15:29
  • 4
    Possible duplicate of [What does "dereferencing" a pointer mean?](https://stackoverflow.com/questions/4955198/what-does-dereferencing-a-pointer-mean) – NonCreature0714 Apr 02 '18 at 15:35

1 Answers1

1

I wonder when I change *ptr to 9, why does the value of "value" change according to *ptr?

Because ptr points to value. The result of the indirection operation is an l-value that designates the pointed object.

eerorika
  • 232,697
  • 12
  • 197
  • 326