Search code examples
cmemory-addressvoid-pointers

Print the addresses of all the bytes occupied by an integer variable


Here's the code -

#include <stdio.h>
int main()
{
    char character_1 = '0';
    int integer_1 = 12321;
    char character_2 = '1';
    char character_3 = '2';

    printf("Integer occupies %zu byte(s) of space.\n",sizeof(int));
    printf("Address of Integer 1: %p\n",(void*)&integer_1);
    printf("\n");

    printf("Character occupies %zu byte(s) of space.\n",sizeof(char));
    printf("Address of Character 1: %p\n",(void*)&character_1);
    printf("Address of Character 2: %p\n",(void*)&character_2);
    printf("Address of Character 3: %p\n",(void*)&character_3);
    printf("\n");
    return 0;
}

and, the generated output -

Integer occupies 4 byte(s) of space.
Address of Integer 1: 000000000061FE18

Character occupies 1 byte(s) of space.
Address of Character 1: 000000000061FE1F
Address of Character 2: 000000000061FE17
Address of Character 3: 000000000061FE16

I want to print the addresses of all the four bytes of space occupied by the integer variable integer_1, which means print all four of these - 000000000061FE18, 000000000061FE19, 000000000061FE1A and 000000000061FE1B. How do I do it?


Solution

  • Is this what you are trying to do?

    #include <stdio.h>
    
    int main()
    {
        int integer_1 = 12321;
        unsigned char* p = (unsigned char*)&integer_1;
        
        for (int i=0; i<sizeof(int); i++){
            printf("Address: %p -> Value: %02hhx\n", p+i, *(p+i));
        }
        return 0;
    }
    

    EDIT: As pointed out by KPCT, working with void* is indeed possible, just a bit more tedious if you are also interested in the value pointed, and not the address only.

    For example, adapting my above solution to use void*, would result in something like this

    #include <stdio.h>
    
    int main()
    {
        int integer_1 = 12321;
        void* p = (void*)&integer_1;
        
        for (int i=0; i<sizeof(int); i++){
            printf("Address: %p -> Value: %02hhx\n", p+i, *((char*) p+i));
        }
        return 0;
    }
    

    where you would have to go through the cast to char* anyway