C Struct 对齐方式

测试程序:

#include "stdio.h"
#include "stdlib.h"

typedef struct _NN_{
    char a[10];   
}sNN;

typedef struct _New_{
    char a;
    char *p;
    int i;
    float f;
    double d;
    sNN sn;
}sNew;

int main()
{
    sNew new;
    printf("sizeof char = %d \n", sizeof(char));
    printf("sizeof pointer = %d \n", sizeof(new.p));
    printf("sizeof int = %d \n", sizeof(int));
    printf("sizeof float = %d \n", sizeof(float));
    printf("sizeof double = %d \n", sizeof(double));
    printf("sizeof NN = %d\n", sizeof(sNN));
    printf("sizeof New = %d\n", sizeof(sNew));
}

输出结果:

sizeof char = 1
sizeof int = 4
sizeof float = 4
sizeof double = 8
sizeof NN = 10
sizeof New = 32

验证方法:
typedef struct _New_{
    char a;
}sNew;
output:
sizeof char = 1
sizeof New = 1

typedef struct _New_{
    char a;
    sNN sn;
}sNew;
output:
sizeof char = 1
sizeof New = 11

typedef struct _New_{
    char a;
    int i;  
}sNew;
output:
sizeof char = 1
sizeof int = 4
sizeof New = 8

typedef struct _New_{
    char a;
    char *p;
}sNew;
output:
sizeof char = 1
sizeof pointer = 4
sizeof New = 8


typedef struct _New_{
    char a;
    double d; 
}sNew;
output:
sizeof char = 1
sizeof double = 8
sizeof New = 12

typedef struct _New_{
    double d; 
    char a;   
}sNew;
output:
sizeof char = 1
sizeof double = 8
sizeof New = 12


typedef struct _New_{
    char a;
    int i;  
    double d;
}sNew;
output:
sizeof char = 1
sizeof int = 4
sizeof double = 8
sizeof New = 16


typedef struct _New_{
    char a;
    int i;
    float f;
    double d;
    sNN sn;
}sNew;
output:
sizeof char = 1
sizeof int = 4
sizeof float = 4
sizeof double = 8
sizeof NN = 10
sizeof New = 32

typedef struct _New_{
    char a;
    int *p;
    char b[10];
}sNew;
output:
sizeof char = 1
sizeof pointer = 4
sizeof New = 20

综上说明:
1. 当数组只有以char为元素构成时,包括char元素和char数组,struct的大小由char元素的个数加上所有char数组的大小。
2. 当数组出现非char元素(int,float,double,struct)组成的成员时,char成员与4Byte对齐。char数组或只有char构成的struct成员也与4Byte对齐。
3. 指针成员的大小可根据本地机器的位数决定,一般与int得大小相等。
4. 成员的先后顺序对struct 的大小没有关系。




你可能感兴趣的:(c,struct,职场,休闲)