2.8.25

Understanding Pointers



Program: Understanding Pointers 

#include <stdio.h>

int main() {
    int a = 10;          
    int *p;              

    p = &a;              
    
    printf("Value of a: %d\n", a);
    printf("Address of a: %p\n", &a);
    printf("Value stored in p (address of a): %p\n", p);
    printf("Value pointed to by p: %d\n", *p); // dereferencing

    
    *p = 20;
    printf("\nAfter changing *p to 20:\n");
    printf("New value of a: %d\n", a);
    
    return 0;
}

Explanation 

Code what does it do?
int a = 10;         Declares an integer a and sets it to 10.
int *p;         Declares a pointer p that can store the address of an integer.
p = &a;         Stores the address of a into p. Now p “points to” a.
*p         Dereferences the pointer, i.e., gets the value stored at the address in p.
*p = 20;         Changes the value at the address stored in p to 20 (so a becomes 20).

What you’ll see in output:

Value of a: 10
Address of a: 0x7ffee63b4a5c       
Value stored in p (address of a): 0x7ffee63b4a5c
Value pointed to by p: 10

After changing *p to 20:
New value of a: 20

Key Things:

  • Pointer (*p): A variable that stores the address of another variable.

  • Address-of (&a): Gets the memory address of variable a.

  • Dereferencing (*p): Accesses the value stored at the address the pointer points to.


No comments:

Post a Comment

rating System

Loading...

Understanding Arrays in C

The Bookshelf Analogy & Book-Author Example Arrays are one of the most essential concepts in C programming. They let you store multiple ...