How will you show memory representation of C variables?

CServer Side ProgrammingProgramming

Here we will see how to print the memory representation of C variables. Here we will show integers, floats, and pointers.

To solve this problem, we have to follow these steps −

  • Get the address and the size of the variable
  • Typecast the address to the character pointer to get byte address
  • Now loop for the size of the variable and print the value of typecasted pointer.

Example

#include <stdio.h>
typedef unsigned char *byte_pointer; //create byte pointer using char*
void disp_bytes(byte_pointer ptr, int len) {
    //this will take byte pointer, and print memory content
   int i;
   for (i = 0; i < len; i++)
      printf(" %.2x", ptr[i]);
   printf("\n");
}
void disp_int(int x) {
   disp_bytes((byte_pointer) &x, sizeof(int));
}
void disp_float(float x) {
   disp_bytes((byte_pointer) &x, sizeof(float));
}
void disp_pointer(void *x) {
   disp_bytes((byte_pointer) &x, sizeof(void *));
}
main() {
   int i = 5;
   float f = 2.0;
   int *p = &i;
   disp_int(i);
   disp_float(f);
   disp_pointer(p);
   disp_int(i);
}

Output

05 00 00 00
00 00 00 40
3c fe 22 00 00 00 00 00
05 00 00 00
raja
Published on 03-May-2019 11:07:05
Advertisements