1

For an assignment I came across this question.

What is the result of the statement following the definitions given below?

    char c='a';
    char *pc=&c;
    char *&rc=pc ;
    (*rc)++;

after printing all the different variables it shows that now variable c stores 'b'. I didn't understand why. Can anyone please explain?

salahuddin
  • 13
  • 2
  • Have you tried stepping through the code with a debugger and seeing how the variables change? – Quimby Oct 12 '22 at 09:59
  • Did you read your C++ student book, chapters about references and pointers? If not you should do it instead posting question on SO. Reading documentation/instruction/books is one of most important skills in coding. If you did please focus your question on what didn't you understood from this chapters. – Marek R Oct 12 '22 at 10:08
  • 1
    @MarekR A lot of basic questions have been asked on SO, which pop up first in google when you search. I don't see the point of discouraging people asking a basic question on SO. – Karen Baghdasaryan Oct 12 '22 at 10:23
  • @KarenBaghdasaryan I'm not discouraging to asking question on SO. I'm encouraging to properly use existing resources. Giving strait answer in this case will spoil future developer. IMO it is better to point someone to correct direction to make him more independent and more skillful. – Marek R Oct 12 '22 at 10:27

1 Answers1

0

Both char** (pointer-to-pointer) and char*& (reference-to-pointer) are second level abstractions of a value. (There's no pointer-to-reference type btw.)

The differences are really the same as they are for regular pointers vs. references: nullable vs. non-nullable etc. See here for more: https://www.geeksforgeeks.org/pointers-vs-references-cpp/

In your example, incrementing *rc does the same as would with using *pc. Note that you don't need a symbol for accessing a references value as you would with * when using a pointer.

Just for fun: Try char** ppc = &pc. Can you tell what this does ?

nick
  • 541
  • 1
  • 9
  • 1
    thanks. I understand now. char** ppc = &pc; this double pointer or pointer-to-pointer stores the address of pc and it can modify variable c by **ppc = 'e'; – salahuddin Oct 12 '22 at 11:26
  • @salahuddin: Right on :) If you like it, please accept my answer. – nick Oct 13 '22 at 08:25