Search code examples
cpointers

Why does changing a pointer type by casting not change the resulting pointer value?


If I cast a pointer from int32_t to int8_t, why does the pointer's value not change? I expected the resulting value to change from a 32-bit address to an 8-bit address.

When experimenting with the code below, it does not change. Why?

#include <stdio.h>
#include <stdint.h>

int main()
{
    int32_t * first = (int32_t *) 0xFFFFFFFF;
    int8_t * second = (int8_t *) first;

    printf("Gives: %p \n", first);
    printf("Gives: %p \n", second);

    return 0;
}

Solution

  • If I cast a pointer from int32_t to int8_t, why does the pointer's value not change? I expected the resulting value to change from a 32-bit address to an 8-bit address.

    Both first and second are pointers. first is pointing to an int8_t object, and second is pointing to an int32_t object.

    The 8 in int8_t * denotes the number of bits in the pointed-to object, and not the pointer. The 32 in int32_t * denotes the number of bits in the pointed-to object, and not the pointer.


    Side-note: %p expects void *, not uint8_t * or uint32_t *. If an argument does not match the corresponding format specifier, the behavior is undefined.