SIZEOF函数使用

参考  http://blog.csdn.net/wzy198852/article/details/7246836

1.语法

sizeof有三种语法形式,如下:
1) sizeof( object ); // sizeof( 对象 );
2) sizeof( type_name ); // sizeof( 类型 );
3) sizeof object; // sizeof 对象;

2.计算

1)计算求值

  sizeof(2) = sizeof(int);  sizeof(2.22) = sizeof(double)

2)函数求值,得到函数的返回值类型所占字节的大小,不会去执行调用函数

  int func(void);

  sizeof(func) = sizeof(int)

3)数组求值

void FuncArray(char *a)

{

  printf("%d ", sizeof(a));  /* 4,32位编译器指针占4个字节,64位编译器指针占8个字节 */

}

int main(void)
{

   /* 数组指针 */
  char a[] = "abc";
  printf("%d ", sizeof(a));   /* 4,包含结束符 '' */
  printf("%d ", strlen(a));   /* 3,不包含结束符*/

  int b[4];

  printf("%d ", sizeof(b)); /* 16 */

  /* 如果数组名被当做参数传入函数 */

  FuncArray(a);

  return 0;
}

4)结构体求值 

struct S1
{
  char c;  //4
  int i;     //4
};

printf("%d ", sizeof(S1));   /* 8,结构体对齐  */

#include<stdio.h>
void test_str(void)
{
  struct Ele{
    char a;       //1
    short b;        //2
    int c;                 //4+1
    long long int d;   //8
  }tEle,*pEle;


  printf("...%lu,%lu,%lu,%lu",sizeof(tEle),sizeof(&tEle),sizeof(pEle),sizeof(*pEle));   //16 4/8 4/8 16


int main()
{
  test_str(); 
}

为什么需要字节对齐?这样有助于加快计算机的取数速度,否则多花指令周期

如果加上结构体对齐指令

#pragma pack(push)   // 将当前pack设置压栈保存
#pragma pack(2)     // 必须在结构体定义之前使用 ,设置为2个字节对齐
struct S1
{
char c;  //2
int i;      //4
};
struct S3
{
char c1;
S1 s;
char c2
};
#pragma pack(pop) // 恢复先前的pack设置

sizeof(S1) = 6

sizeof(S3) = 10

原文地址:https://www.cnblogs.com/Deanboy/p/7537715.html