top of page

Pointer Variable

  • Writer: Siddharth Sharma
    Siddharth Sharma
  • Nov 7, 2024
  • 2 min read

A pointer variable is a special type of variable that stores the memory address of another variable rather than storing a data value itself. In other words, a pointer points to the location in memory where data is stored.


Key Points about Pointer Variables

  • Declaration: Pointer variables are declared with a * (asterisk) symbol before the variable name. The type of the pointer is the same as the type of the variable it points to.

  • Initialization: A pointer variable is typically initialized to the memory address of an existing variable, using the address-of operator &.

  • Dereferencing: Using the dereference operator *, we can access or modify the value stored at the memory address pointed to by the pointer.


Example of a Pointer Variable in C

Here’s an example demonstrating how to declare, initialize, and use a pointer variable in C:

#include <stdio.h>

int main() {
    int num = 10;       // Regular integer variable
    int* ptr = &num;    // Pointer variable that holds the address of num

    // Displaying the value and address
    printf("Value of num: %d\n", num);         // Outputs 10
    printf("Address of num: %p\n", (void*)ptr); // Outputs the memory address of num
    printf("Value at ptr: %d\n", *ptr);        // Outputs the value at the memory address ptr holds (10)

    // Modifying the value through the pointer
    *ptr = 20;
    printf("Modified value of num: %d\n", num); // Outputs 20

    return 0;
}

Explanation of the Code:

  • int num = 10; declares an integer variable num and initializes it to 10.

  • int* ptr = &num; declares a pointer variable ptr that holds the address of num.

  • *ptr = 20; modifies the value at the memory address that ptr points to, updating num to 20.


Output:

Value of num: 10
Address of num: [some memory address]
Value at ptr: 10
Modified value of num: 20

Summary:

  • A pointer variable holds a memory address instead of a direct value.

  • Pointers provide powerful ways to manipulate data, especially for passing values by reference, dynamic memory allocation, and creating complex data structures.


 
 
 

Comments


bottom of page