CodeBlanks Logo Icon CodeBlanks

Pointer dereference

Learn to access the value a pointer points to with *.

Pointer dereference with *

The * operator reads (or writes) the value at the address a pointer holds. This is called dereferencing.

int x = 10;
int *ptr = &x;
printf("%d\n", *ptr);  /* prints 10 */
*ptr = 20;  /* x is now 20 */

*ptr works for both reading and writing. Assignment changes the value at the pointed address; it changes x, not ptr.

Changing a value via dereference

The assignment *ptr = value; writes to the address the pointer holds. So the variable ptr points to changes.

int x = 5;
int *ptr = &x;
*ptr = 99;  /* x is now 99 */
printf("%d\n", x);  /* prints 99 */

This is the basis for functions changing original variables. The function takes a pointer, writes to the address with *.

Practice Change a value via dereference and print

Define int x = 5;. Bind with int *ptr = &x;. Set x to 30 with *ptr = 30;. Print with printf("%d\n", x);. Output should be 30.

Starter code

main.c
#include <stdio.h>

int main(void) {
    int x = 5;
    /* bind ptr to x */
    /* set x to 30 via dereference */
    /* print x with printf %d */
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int x = 5;
    int *ptr = &x;
    *ptr = 30;
    printf("%d\n", x);
    return 0;
}

Expected output

30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match pointer operators

Term Meaning
& takes address
* dereferences
int * pointer type
NULL null pointer

2 Read a value via dereference

Question
int x = 7;
int *ptr = &x;
printf("%d\n", ____);  /* prints 7 */
Answer
int x = 7;
int *ptr = &x;
printf("%d\n", *ptr);  /* prints 7 */

Explanation: *ptr gives the value ptr points to.

3 What does `*ptr = 99;` change?

  • ptr itself
  • The variable ptr points to Correct answer
  • Nothing
  • Only ptr's address

Explanation: *ptr assignment writes to the address ptr points to; that variable changes.

All lessons in Beginner