• Home
  • Pointer Basics – Example 2

Pointer Basics – Example 2

View Categories

Pointer Basics – Example 2

< 1 min read

This example extends pointer usage by showing how to access the value stored at the address held by a pointer. Pointers store addresses, and dereferencing is used to read or modify the value at that address.



⚙️
main.c

Copy to clipboard

#include <stdio.h>

int main()
{
    int x = 5;
    int *ptr;

    ptr = &x;

    printf("x = %d\n", x);
    printf("Value at address pointed by ptr = %d\n", *ptr);

    return 0;
}

Output:
x = 5
Value at address pointed by ptr = 5

ptr is a pointer to an integer and stores the address of x.

A pointer should always hold a valid memory address. Instead of assigning a random address, a variable is defined so that memory is allocated, and its address can be used.

The address of a variable is obtained using the & operator.
ptr = &x stores the address of x in ptr.

To access the value stored at that address, the dereferencing operator * is used.

*ptr reads the value present at the memory location pointed to by ptr, which is the value of x.

printf() uses %d to print integer values.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *