- Write a program in C to show hexadecimal memory representation of a variable.
Algorithm to print memory representation of a variable
- Get the base address of the variable using address of(&) operator and size of variable in bites using sizeof() operator.
- Type cast the base address of variable to character pointer.
- Now, iterate for size of variable(one byte at a time) and print hexadecimal representation of memory location using %x format specifier of printf function.
C program to print memory representation of a variable
#include <stdio.h> /* This function takes base address of a memory location(variable) and print 'size' bytes from 'address' in hexadecimal format */ void printBytes(unsigned char *address, int size) { int count; for (count = 0; count < size; count++){ printf("%.2x ", address[count]); } printf("\n"); } int main() { int i = 1; float f = 5.0; int *ptr = &i; /* print memory map of integer */ printBytes((unsigned char *)&i, sizeof(int)); /* print memory map of float */ printBytes((unsigned char *)&f, sizeof(float)); /* print memory map of pointer */ printBytes((unsigned char *)&ptr, sizeof(int *)); return 0; }Output
01 00 00 00 00 00 a0 40 4c fe 22 00 00 00 00 00