C语言定义结构体时注意成员变量的类型和声明顺序

来源:互联网 发布:nginx 浏览器缓存设置 编辑:程序博客网 时间:2024/05/16 02:07

定义结构体时候,结构体内的变量的声明顺序决定了结构体所占用的内存大小(内存的边界对齐原因)。

不多说,直接上代码:

#include <stdio.h>#include <stdlib.h>#include <iostream>#include <string>#include <cstring>using namespace std;struct node1 //这个node占了32个字节{    int a;    float f;//a 和 f 一共占8个字节    char c;//虽然c只有一个字节,但单独占了8个字节(需要内存对齐)    double d;// 很显然,占8个字节    struct node* next;//指针变量虽然4个字节,但也单独占8个字节};struct node2 //这个node占了24个字节,比上一个node要节省内存{    int a;    float f;//a 和 f 一共占8个字节    char c;    struct node* next;//c和next 一共占用8个字节    double d;//占用8个字节};int main(){    struct node1* p1;    struct node1 anode1;    struct node2* p2;    struct node2 anode2;    printf("%d %d\n",sizeof(p1),sizeof(anode1));    printf("%d %d\n",sizeof(p2),sizeof(anode2));    return 0;}
运行结果:

4    32

4    24

0 0