sizeof - 指针,数组,变量,结构体字节对齐-计算

例子:

#include <stdio.h>
struct
{
        short a1;
        short a2;
        short a3;
}A;
struct
{
        long a1;
        short a2;
}B;

int main()
{
        char * ss1="0123456789";
        char ss2[]="0123456789";
        char ss3[100]="0123456789";
        int ss4[100];
        char q1[]="abc";
        char q2[]="a\n";
        char * q3="a\n";
        char *str1=(char *)malloc(100);
        void *str2=(void *)malloc(100);
        printf("%d\n",sizeof(ss1));
        printf("%d\n",sizeof(ss2));
        printf("%d\n",sizeof(ss3));
        printf("%d\n",sizeof(ss4));
        printf("%d\n",sizeof(q1));
        printf("%d\n",sizeof(q2));
        printf("%d\n",sizeof(q3));

        printf("%d\n",sizeof(A));
        printf("%d\n",sizeof(B));
        printf("%d\n",sizeof(str1));
        printf("%d\n",sizeof(str2));
        return 0;
}

[root@localhost ccy]# ./a.out 
4
11
100
400
4
3
4
6
8
4

4


32位:

long - 4字节

short - 2字节

指针 - 4字节

定长数组 int a[100] - 长度*类型 - 100*4字节

不定长数组 char a[]="123" - 3+"\0" = 4字节

B结构体 - 8字节

因为a1为long为4字节,所有这个B结构体以4字节方式对齐,即a2为short 2字节,但B结构体总长度为8字节;

例如:

struct

{

int a1;

char a2;

}C;//8字节

struct

{

int a1;

char a2;

char a3;

}C;//8字节

struct

{

int a1;

char a2;

char a3;

char a4;

char a5;

char a6;

}C;//12字节


再经典一点:

struct
{
        int a1;
        char a2;
        char a3;
        char a4;
        char a5;
}C1;//8字节

struct
{
char a2;

int a1;
char a3;
char a4;
char a5;
}C2;//12字节

一、C1结构体-8字节

|---------------int--------------|

|-char-|-char-|-char-|-char-|

二、C2结构体-12字节

|-char-|-------|-------|-------|

|---------------int--------------|

|-char-|-char-|-char-|-------|


最近有看到更经典的例子:

struct

{

int a1;

short a2;

char a3[2];

}C;

|---------------int--------------|

|------short-----|-char-|-char-|


struct

{

short a1;

int a2;

char a3[2];

}D;

|------short-----|--------------|

|---------------int--------------|

|-char-|-char-|--------|--------|




你可能感兴趣的:(sizeof - 指针,数组,变量,结构体字节对齐-计算)