Assignment Operators

What Are the & and * Operators in C?

The & operator gets the address of a variable and the * operator reads or changes the value at an address. Here is how both work, with code examples.

On this page
  1. The short answer
  2. The address-of operator: &
  3. The dereference operator: *
  4. A complete example
  5. The same symbols mean other things
  6. Pointers must point to a valid object
  7. Assigning to a pointer and through it

The short answer

The & operator gives you the address of a variable. The * operator, used on a pointer, gives you the value stored at that address, and it can also be assigned to. Both appear in pointer code, and the same symbols mean other things in other places.

The address-of operator: &

&score is the memory address where score is stored. You can take the address only of something that has one, such as a variable. An address is kept in a pointer variable, which is declared with *:

int score = 10;
int *p = &score;  /* p holds the address of score */

Here the * in the declaration says that p is a pointer to an int.

The dereference operator: *

Used on a pointer, * reaches the value at the address the pointer holds. That makes it possible to read or change the variable through the pointer:

*p = 25;  /* writes 25 into the variable p points to */

A complete example

This program changes score through the pointer:

#include <stdio.h>

int main(void) {
    int score = 10;
    int *p = &score;  /* p stores the address of score */

    *p = 25;          /* writes 25 into the variable p points to */
    printf("%d\n", score);  /* prints 25 */
    return 0;
}

The same symbols mean other things

  • Between two values, * is multiplication, so 2 * 3 is 6.
  • Between two values, & is bitwise AND.
  • In C++, & also marks a reference when a variable is declared, as in int &r = score;. C has no references.

Pointers must point to a valid object

Using * on a pointer that holds no valid address, such as an uninitialized pointer or a null pointer, has undefined behavior. Make sure a pointer points to a real object before you read or write through it.

Assigning to a pointer and through it

These two statements do different things:

p = &other;  /* p now points to other; score is unchanged */
*p = 40;     /* the value of the variable p points to is now 40 */

The first changes which variable p points to. The second changes the value stored in that variable.

The complete guide to assignment operators

Assignment Operators in C++
Read the guide

Keep exploring

Guides from other topics

All topics →