-9

What is the difference between these two operators? My understanding is that they both point to the memory location of the variable they are used on.

Ex.

int p; foo(*p,&p); 
4
  • 6
    Get a good book Commented Feb 12, 2020 at 0:53
  • The expression &p returns the location (address) of the variable p. The expression *p return the value that is at the location inside the p variable, often called dereferencing. So if p contains the value 2020, then *p will return the integer stored at location 2020 (if possible). Commented Feb 12, 2020 at 0:56
  • @ThomasMatthews In the code in the question, *p will not compile. The operand of unary * must be an expression of pointer type. A pointer cannot contain the value 2020 (which is of type int), though it might contain, for example, the value (int*)2020. Commented Feb 12, 2020 at 1:13
  • @KeithThompson "The operand of unary * must be an expression of pointer type" - or an instance of a class/struct type that implements a member operator*. Commented Feb 12, 2020 at 1:17

2 Answers 2

0

&p gets the pointer to the integer p -> That is, the memory address in which p is stored.

*p "dereferences" the pointer, i.e. looks at the object at the memory address provided by p and returns that object.

Your code above is invalid C, as you cannot dereference an int:

error: indirection requires pointer operand ('int' invalid)

Consider instead the following:

// Create an integer int p = 1234; printf("Integer: %d\n", p); // Get the pointer to that integer, i.e. the memory address in which p is stored int *pointer = &p; printf("Pointer: %p\n", pointer); // Dereference the pointer to get the value back int q = *pointer; printf("Dereferenced: %d\n", q); 

Gives the following output:

Integer: 1234 Pointer: 0x7ffee53fd708 Dereferenced: 1234 

Also notice that to print out a pointer address, we have to use a special format specifier %p instead of the %d we'd use for an int.

Sign up to request clarification or add additional context in comments.

2 Comments

The code above has no behavior, nasty or otherwise. Given int p;, the expression *p will not compile.
Fair point :) I'll update my answer.
0
// declare an integer int p = 42; // declare a pointer type, and use it to store the address // of the variable p. int* ptr = &p; // use the * to dereference the pointer, and read the integer value // at the address. int value = *ptr; 

Comments