Search code examples
cfunction-pointers

What's the difference between a pointer, and a pointer variable?


I know this is very basic but it is little bit confusing to me.
I've read:

a pointer is nothing more than an address, and a pointer variable is just a variable that can store an address.
When we store the address of a variable i in the pointer variable p, we say that p points to i.

int i, *p = &i;

p points to i.

To gain access to the object that a pointer points to, we use the * (indirection) operator.

If p is a pointer then *p represents the object to which p currently points.

Now I am confused that what should I call p -- pointer or pointer variable?

Additional: Is a pointer always the same as an address?


Solution

  • The difference between a pointer value and a pointer variable is illustrated by:

    int swap_int(int *i1, int *i2)
    {
        int t = *i1;
        *i1 = *i2;
        *i2 = t;
    }
    
    int main(void)
    {
        int  v1 = 0;
        int  v2 = 37;
        int *p2 = &v2;
        printf("v1 = %d, v2 = %d\n", v1, v2);
        swap_int(&v1, p2);
        printf("v1 = %d, v2 = %d\n", v1, v2);
        return 0;
    }
    

    Here, p2 is a pointer variable; it is a pointer to int. On the other hand, in the call to swap_int(), the argument &v1 is a pointer value, but it is in no sense a pointer variable (in the calling function). It is a pointer to a variable (and that variable is v1), but simply writing &v1 is not creating a pointer variable. Inside the called function, the value of the pointer &v1 is assigned to the local pointer variable i1, and the value of the pointer variable p2 is assigned to the local pointer variable i2, but that's not the same as saying &v1 is a pointer variable (because it isn't a pointer variable; it is simply a pointer value).

    However, for many purposes, the distinction is blurred. People would say 'p2 is a pointer' and that's true enough; it is a pointer variable, and its value is a pointer value, and *p2 is the value of the object that p2 points to. You get the same blurring with 'v1 is an int'; it is actually an int variable and its value is an int value.