分享

C基础,sizeof的用法等

 心不留意外尘 2016-05-12

http://blog.csdn.net/ameyume/article/details/5893686

2010

  1. typedef struct _st{  
  2.     int a;  
  3.     int b;  
  4.     char c;  
  5. }st;  
  6.   
  7. struct _struTest  
  8. {  
  9.     short sh;  
  10.     long ln;  
  11. }struTest;  
  12.   
  13. int _tmain(int argc, _TCHAR* argv[])  
  14. {  
  15.   
  16.     char arr[] = "123456789";  
  17.     char *p1 = "12345";  
  18.     char *p2 = arr;  
  19.     int iNum = 10;  
  20.   
  21.     printf("sizeof(arr) = %d/n", sizeof(arr)); // sizeof(arr) = 10, including the end charactor '/0'  
  22.     printf("strlen(arr) = %d/n", strlen(arr)); // strlen(arr) = 9  
  23.     printf("sizeof(p1) = %d/n", sizeof(p1)); // sizeof(p1) = 4  
  24.     printf("sizeof(p2) = %d/n", sizeof(p2)); // sizeof(p2) = 4  
  25.     printf("sizeof(iNum) = %d/n", sizeof(iNum)); // sizeof(iNum) = 4  
  26.   
  27.     int a1 = -2147483648, a2 = 2147483647;  
  28.     if (a1 > a2) // false  
  29.     {  
  30.         printf("a1 > a2/n");  
  31.     }  
  32.   
  33.     if (a1 - a2 > 0) // true  
  34.     {  
  35.         printf("a1 - a2 > 0/n"); // output a1 - a2 > 0  
  36.         printf("a1 - a2 = %d/n", a1 - a2); // output a1 - a2 = 1  
  37.     }  
  38.   
  39.     printf("sizeof(char) = %d/n", sizeof(char));  
  40.     printf("sizeof(short) = %d/n", sizeof(short));  
  41.     printf("sizeof(int) = %d/n", sizeof(int));  
  42.     printf("sizeof(long) = %d/n", sizeof(long));  
  43.     printf("sizeof(st) = %d/n", sizeof(st)); // 字节对齐,以int为准  
  44.     printf("sizeof(struTest) = %d/n", sizeof(struTest)); // 字节对齐,以long为准  
  45.       
  46.   
  47.   
  48.     system("Pause");  
  49.   
  50.     return 0;  
  51. }  

 

32位系统下的输出结果:

sizeof(arr) = 10 // 数组的长度,数组会自动加一个结束符'/0'
sizeof(p1) = 4 // 输出的是指针的长度4
sizeof(p2) = 4 // 输出的是指针的长度4
sizeof(iNum) = 4 // 输出的是int型变量的长度4
a1 - a2 > 0
a1 - a2 = 1

sizeof(char) = 1
sizeof(short) = 2
sizeof(int) = 4
sizeof(long) = 4
sizeof(st) = 12
sizeof(struTest) = 8

 

由输出结果可以知道,判断条件a1 > a2 与a1 - a2 > 0的结果是不一样的。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多