Cover Image for C Dereference Pointer
133 views

C Dereference Pointer

The process of accessing the value stored at a memory location pointed to by a pointer is called “dereferencing” a pointer. Dereferencing is performed using the unary * operator. When you use * followed by a pointer variable, it retrieves the value stored at the memory address the pointer is pointing to.

Here’s an example of dereferencing a pointer:

C
#include <stdio.h>

int main() {
    int x = 42;         // Declare an integer variable x and assign it a value
    int *ptr = &x;      // Declare a pointer ptr and initialize it with the address of x

    printf("Value of x: %d\n", x);            // Prints the value of x
    printf("Value via pointer: %d\n", *ptr);  // Dereferencing ptr to get the value of x

    return 0;
}

In this example:

  1. We declare an integer variable x and assign it a value of 42.
  2. We declare a pointer ptr and initialize it with the address of x using the address-of operator &.
  3. To access the value stored at the memory location pointed to by ptr, we use *ptr. The expression *ptr dereferences the pointer and retrieves the value stored in x.
  4. We use printf to print both the value of x and the value accessed via the pointer ptr.

When you run this program, it will display:

Plaintext
Value of x: 42
Value via pointer: 42

Dereferencing pointers is essential in C programming when you want to manipulate or access data stored in memory through pointer variables. It allows you to work with the values that pointers point to, making pointers a powerful tool for memory management and data manipulation in C.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS