• Home
  • Pointer Basics – Cross Accessing Different Pointer Types

Pointer Basics – Cross Accessing Different Pointer Types

View Categories

Pointer Basics – Cross Accessing Different Pointer Types

< 1 min read

This example shows what happens when the same memory location is accessed using pointers of different types. The way data is read or modified depends on the pointer type used for dereferencing.



⚙️
main.c

Copy to clipboard

#include <stdio.h>

int main()
{
    int num = 0x12345678;

    int *ptr = &num;
    char *cptr = (char *)&num;

    int int_val;
    char char_val;

    int_val = *ptr;
    char_val = *cptr;

    printf("*ptr = %x, int_val = %x\n", *ptr, int_val);
    printf("*cptr = %x, char_val = %x\n", *cptr & 0xFF, char_val & 0xFF);

    *cptr = 0x55;

    printf("*cptr = %x\n", *cptr & 0xFF);
    printf("*ptr = %x\n", *ptr);

    return 0;
}

Output:
*ptr = 12345678, int_val = 12345678
*cptr = 78, char_val = 78
*cptr = 55
*ptr = 12345655

ptr is an int *, so dereferencing reads 4 bytes (on most systems).
cptr is a char *, so dereferencing reads only 1 byte.

Both pointers refer to the same memory location (num), but interpret it differently.

char_val = *cptr reads the lowest byte of num. The exact byte accessed depends on system endianness.

Modifying *cptr updates only one byte of the integer.
After *cptr = 0x55, the least significant byte of num changes.

Accessing the same memory using different pointer types leads to different views of the same data.

Powered by BetterDocs

Leave a Reply

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