Search code examples
c++cpointersreferencedereference

Can a pointer point to a value and the pointer value point to the address?


Normal pointer usage as I have been reading in a book is the following:

int *pointer;
int number = 5;
pointer = &number; 

Then *pointer has a value of 5. But does this work the other way around? I mean:

int *pointer;
int number = 5;
*pointer = &number;

Here does pointer contain the value 5 and *pointer holds the address of number?

Thanks.


Solution

  • Analogy from the department of far-fetched analogies:

    You use pointers many times every day without even thinking about it.

    A pointer is an indirection - it tells you where something is, or how it can be reached, but not what that thing is.
    (In a typed language, you can know what kind of thing it is, but that's another matter.)

    Consider, for example, telephone numbers.

    These tell you how to reach the person that the phone number belongs to.
    Over time, that person may change - perhaps somebody didn't pay their bills and the number was reassigned - but as long as the number is valid, you can use it to reach a person.

    Using this analogy, we can define the following operations:

    • &person gives you a person's phone number, and
    • *number gives you the person that the number belongs to.

    Some rules:

    • There are only two types in this language - persons and phone numbers.
    • Only persons can have phone numbers; &number is an error, as is *person.
    • An unspecified phone number reaches the General Manager of Customer Services at Acme, Inc.

    Now, your first example would translate to

    PhoneNumber n;
    Person Bob;
    n = &Bob;
    

    which makes sense; n now holds Bob's phone number.

    Your second example would translate to

    PhoneNumber n;
    Person Bob;
    *n = &Bob;
    

    which would say "replace the General Manager of Acme Inc's Customer Services with Bob's phone number", which makes no sense at all.

    And your final question,

    Here does pointer contain the value 5 and *pointer holds the address of number?

    would translate to

    Is this phone number the same thing as Bob, and if you call it, will Bob's phone number answer?

    which I am sure you can see is a rather strange question.