美文网首页
sizeof(struct)

sizeof(struct)

作者: 远o_O | 来源:发表于2017-08-24 14:39 被阅读4次
  • 在C语言中,结构体会以占用字节最长的变量为基准,做内存对齐。
#include<iostream>
#include<stdlib.h>
using namespace std;

struct A
{
    //4+4 = 8
    char c;
    int i;  
};

struct B
{
    //4+8+4 = 16 
    char c;
    A a;
    char b;
};

struct C
{
    //4 + 4*4 + 4 = 24
    char c;
    int a[4];
    int i;  
};

struct D
{   
    //4 + 4 = 8
    char c;
    char b;
    int q;  
};

struct E
{
    //8+8 = 16,以最大的为准,进行对齐填充 
    int a;
    double b;   
};

struct F
{   
    //1 + 1 = 2
    char a;
    char b;
};

int main()
{   
    cout<<"the sizeof struct A: "<<sizeof(A)<<endl;
    cout<<"the sizeof struct B: "<<sizeof(B)<<endl;
    cout<<"the sizeof struct C: "<<sizeof(C)<<endl;
    cout<<"the sizeof struct D: "<<sizeof(D)<<endl;
    cout<<"the sizeof struct E: "<<sizeof(E)<<endl;
    cout<<"the sizeof struct F: "<<sizeof(F)<<endl;
    return 0;   
} 
image.png

相关文章

  • sizeof(struct)

    在C语言中,结构体会以占用字节最长的变量为基准,做内存对齐。

  • 这可能是你看过的关于C/C++内存对齐最好的文章

    写出一个struct,然后sizeof,你会不会经常对结果感到奇怪?sizeof的结果往往都比你声明的变量总长度要...

  • C 笔记

    0722 结构体指针加1后,指针的偏移量为sizeof(struct); 示例代码如下: 运行结果如下: 0723...

  • 内存大小,内存对齐

    一、结构体 此时执行sizeof(struct Student1),结果是8交换成员变量的顺序 此时执行sizeo...

  • 编译时检查sizeof

    需求:在编译时检查struct数据结构的大小 思路a:预编译时检测,不一定支持sizeof,且数据结构类型未知。 ...

  • C初阶8:联合体

    语法 用法与struct一样。不同点是所有成员公用相同的内存空间。联合体的sizeof是成员中大小最大的值。 联合...

  • data alignment 和 data padding

    开门见山,下面代码占据了几个字节: 最开始在不懂的时候也以为是5字节,但是如果用sizeof(struct foo...

  • 布尔

    sizeof(BOOL) = 1sizeof(bool) = 1sizeof(Boolean) = 1

  • 【C语言】3.sizeof

    1.sizeof sizeof并不是函数,而是运算符。可以用sizeof计算有多少字节。通常用sizeof(常量/...

  • C 基本数据类型内存

    sizeof long int=4; //这与int一样 sizeof shor int=2; sizeof do...

网友评论

      本文标题:sizeof(struct)

      本文链接:https://www.haomeiwen.com/subject/nahedxtx.html