Write a C program to show memory representation of C variables like int, float, pointer, etc.

Algorithm: Get the address and size of the variable. Typecast the address to char pointer. Now loop for size of the variable and print the value at the typecasted pointer.

Program:

#include <stdio.h>
typedef unsigned char *byte_pointer;
 
/*show bytes takes byte pointer as an argument
   and prints memory contents from byte_pointer
   to byte_pointer + len */
void show_bytes(byte_pointer start, int len)
{
      int i;
      for (i = 0; i < len; i++)
            printf ( " %.2x" , start[i]);
      printf ( "\n" );
}
 
void show_int( int x)
{
      show_bytes((byte_pointer) &x, sizeof ( int )); //强制类型转换,将地址指向的内容变成char类型
}
 
void show_float( float x)
{
      show_bytes((byte_pointer) &x, sizeof ( float ));//sizeof字节数:具体解释见下面
}
 
void show_pointer( void *x)
{
      show_bytes((byte_pointer) &x, sizeof ( void *)); //指向空类型的指针,不指定类型
}
 
/* Drover program to test above functions */
int main()
{
     int i = 1;
     float f = 1.0;
     int *p = &i;
     show_float(f); //其实可以有好几种传递参数的方式,不过主程序里传递参数尽量明了。
     show_int(i);
     show_pointer(p);
     return 0;
}
补充:

strlen()和sizeof()

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #define PRAISE "What a super marvelous name!"  
  4. int main(void)  
  5. {  
  6.     char name[40] = "Morgan";  
  7.     printf("strlen = %d\nsizeof = %d\n",strlen(name), sizeof(name));  
  8.     printf("strlen = %d\nsizeof = %d",strlen(PRAISE), sizeof(PRAISE));  
  9.     return 0;  
  10.   
  11. }  

输出结果

strlen = 6 sizeof = 40 strlen = 28 sizeof = 29

根据sizeof报告,name有40个字节,不过根据strlen报告只用了其中前6个单元来存放Morgan,第七个字节为空字符,它的存在告诉strlen在哪里停止计数

对于 PRAISE ,strlen给出了准确数目(包括空格和标点符号)

sizeof运算结果比strlen的结果大1,这是因为它把结束字符串也算进去了(/0)你并没有定义存储该语句分配多大内存,计算机自己计算出双引号之间的字符数目。