-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);
n00dle
  • 5,949
  • 2
  • 35
  • 48
  • 6
    [Get a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) – selbie Feb 12 '20 at 00: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). – Thomas Matthews Feb 12 '20 at 00: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`. – Keith Thompson Feb 12 '20 at 01: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*`. – Remy Lebeau Feb 12 '20 at 01:17

2 Answers2

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;
robthebloke
  • 9,331
  • 9
  • 12
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.

n00dle
  • 5,949
  • 2
  • 35
  • 48