0
0
Cprogramming~5 mins

Address and dereference operators

Choose your learning style9 modes available
Introduction

We use address and dereference operators to work with memory locations directly. This helps us access or change the value stored in a specific place in the computer's memory.

When you want to find the memory address of a variable.
When you want to access or change the value stored at a specific memory address.
When working with pointers to handle dynamic data or arrays.
When passing large data to functions efficiently by passing addresses instead of copies.
Syntax
C
int *pointer;  // declare a pointer to int
pointer = &variable;  // & is the address operator
value = *pointer;  // * is the dereference operator

The & operator gives the address of a variable.

The * operator accesses the value stored at the address the pointer holds.

Examples
Here, p stores the address of x. Using *p gets the value of x.
C
int x = 10;
int *p = &x;  // p holds the address of x
int y = *p;   // y gets the value 10 from x
Using *ptr = 20; changes the value stored at the address ptr points to, which is a.
C
int a = 5;
int *ptr = &a;
*ptr = 20;  // changes value of a to 20
Sample Program

This program shows how to get the address of a variable using &, access its value using *, and change the value through the pointer.

C
#include <stdio.h>

int main() {
    int num = 7;
    int *p = &num;  // p stores address of num

    printf("Value of num: %d\n", num);
    printf("Address of num: %p\n", (void*)&num);
    printf("Value stored at pointer p: %d\n", *p);

    *p = 15;  // change value of num using pointer
    printf("New value of num after change: %d\n", num);

    return 0;
}
OutputSuccess
Important Notes

Always initialize pointers before dereferencing to avoid errors.

Use (void*) cast when printing addresses with %p for portability.

Summary

The & operator gets the address of a variable.

The * operator accesses or changes the value at a given address.

Pointers store addresses and allow indirect access to variables.