Home >Backend Development >C++ >How would you display the memory representation of a C variable?

How would you display the memory representation of a C variable?

PHPz
PHPzforward
2023-09-09 13:29:06732browse

How would you display the memory representation of a C variable?

Here we will see how to print the memory representation of a C variable. Here we will display integers, floating point numbers and pointers.

To solve this problem we have to follow the following steps -

  • Get address and size of variable
  • Convert address type to character pointer to get byte address
  • Now loop to get the size of the variable and print the value of the type converted 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("</p><p>");
    }
    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

The above is the detailed content of How would you display the memory representation of a C variable?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete