Search code examples
cpointersmemorymemory-address

Is there a way to print all memory addresses a variable is stored in?


I want to know if there is a way to print all the memory locations that say an int variable is stored in. Example:

#include <stdio.h>

int main()
{
        int x = 5;
        int *y = &x;
        printf("%p", (void*)y);
}

Example output: 0x100000000001

This will show the memory address that the first byte of x is stored in, but I want to see the memory address of each byte that it is stored in. Is there any way to do this? Or do I just assume the following memory place values since they're consecutive? i.e. the other memory locations of this int would be:

0x100000000002?

0x100000000003?

0x100000000004?


Solution

  • a way to print all the memory locations that say an int variable is stored in.

    Sure. Form a loop [0...sizeof(int)).

    int main() {
      int x = 5;
      void *y = &x;
      for (size_t i = 0; i < sizeof x; i++) { 
        printf("%p\n", (void*)((char *)y + i));
      }
    }