当前位置 : 主页 > 编程语言 > c++ >

[c++11]结构体字节对齐

来源:互联网 收集:自由互联 发布时间:2021-06-23
//测试c++中结构体的字节对齐#include iostream#include cmathusing namespace std;void vsVersion();//example 1struct Node1{ char a; int b; double c;};//example 2struct Node2 { char a; int b; char c;};//example 3struct Node3{};//examp
//测试c++中结构体的字节对齐
#include <iostream>
#include <cmath>

using namespace std;
void vsVersion();
//example 1
struct Node1
{
    char a;
    int b;
    double c;
};
//example 2
struct Node2 
{
    char a;
    int b;
    char c;
};
//example 3
struct Node3
{

};
//example 4
struct Node4
{
    char a;
    int b;
    static double c;
};
//example 5

struct Inside 
{
    int a;
    double b;
    float c;
};
struct Node5 {
    char e[2];
    int f;
    short h;
    struct Inside inside;
};
//example 6
struct Node6 {
    char a;
    int b;
    float c;
    double d;
    int* p;
    char* pc;
    short e;
};

int main()
{
    Node1 n1;
    Node2 n2;
    Node3 n3;
    Node4 n4;
    Node5 n5;
    Node6 n6;
    vsVersion();
//宏定义:https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros?redirectedfrom=MSDN&view=vs-2019
#ifdef _WIN64
    cout << "--------x64----------------" << endl;
    cout << "char:" << sizeof(char) << endl;
    cout << "short:" << sizeof(short) << endl;
    cout << "int:" << sizeof(int) << endl;
    cout << "double:" << sizeof(double) << endl;
    cout << "float:" << sizeof(float) << endl;
    cout << "char *:" << sizeof(char *) << endl;
    cout << "Node1 :" << sizeof(n1) << endl;
    cout << "Node2 :" << sizeof(n2) << endl;
    cout << "Node3 :" << sizeof(n3) << endl;
    cout << "Node4 :" << sizeof(n4) << endl;
    cout << "Node5 :" << sizeof(n5) << endl;
    cout << "Node6 :" << sizeof(n6) << endl;
#else
    cout << "--------x86----------------" << endl;
    cout << "char:" << sizeof(char) << endl;
    cout << "short:" << sizeof(short) << endl;
    cout << "int:" << sizeof(int) << endl;
    cout << "double:" << sizeof(double) << endl;
    cout << "float:" << sizeof(float) << endl;
    cout << "char *:" << sizeof(char*) << endl;
    cout << "Node1 :" << sizeof(n1) << endl;
    cout << "Node2 :" << sizeof(n2) << endl;
    cout << "Node3 :" << sizeof(n3) << endl;
    cout << "Node4 :" << sizeof(n4) << endl;
    cout << "Node5 :" << sizeof(n5) << endl;
    cout << "Node6 :" << sizeof(n6) << endl;

#endif


    
    cout << "hello world" << endl;
    return 0;
}

//确定IDE版本
void vsVersion()
{
    if (_MSC_VER == 1921 or _MSC_VER == 1922 or _MSC_VER == 1923)
    {
        cout << "vs2019" << endl;
    }
    else if (_MSC_VER == 1910 or _MSC_VER == 1911 or _MSC_VER == 1912 or _MSC_VER == 1913 or _MSC_VER == 1914 or _MSC_VER == 1915 or _MSC_VER == 1916)
    {
        cout << "vs2017" << endl;
    }
    else
    {
        cout << "others" << endl;
    }

}

网友评论