Home > Backend Development > C++ > body text

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

PHPz
Release: 2023-09-09 13:29:06
forward
688 people have browsed it

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);
    }
    Copy after login

    Output

    05 00 00 00
    00 00 00 40
    3c fe 22 00 00 00 00 00
    05 00 00 00
    Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!