这里有2个知识点你需要关注一下:
1:操作系统的发展过程中,是有16位机器,32位机器,64位机器之说的,一般的 我们说int占用4个字节,是针对大多常用的32/64位操作系统,但是不绝对。
2:结构体有按字节对齐一说,共用体是按成员最大的那个定义内存大小。
这个题目的目的
1:本身应该是想让你关注结构体和共用体在内存分配上的差异。
2:想让你关注结构体内存的大小,是有内存对齐一说的。
至于int类型本身占几个字节,应该是在什么操作系统下的前提下去分析的,不必纠结。
#pragma pack(1)
struct tttt {
char a1;
int a2;
float a3;
};
#pragma pack()
int main()
{
//1+4+4 这里如果操作系统默认会是12
//如果我设置按1字节对齐 就会是9 #pragma pack(1) ...#pragma pack()
printf("%lu \n", sizeof(struct tttt));
return 0;
}
也不对吧。(1+3)+4+4=12,不应该是12?
有的编译器int类型好像是只占2个字节
都不对啊,有结构体对齐的
#define NOMINMAX
// #pragma pack(4) -- align 4 bytes (default ?
#pragma pack(1) // force the compiler to use 1-byte alignment (not align)
// #pragma pack(2) -- align 2 bytes
// string constructor
#include <string.h>
#include <windows.h>
#include <stdio.h>
struct type1 {
char ch; // 1
float f; // 4
short i; // 2
};
struct type2 {
float f; // 4
short i; // 2
char ch; // 1
};
union utype1 {
char ch; // 1
short i; // 2
float f; // 4
};
union utype2 {
char ch; // 1
short i; // 2
float f; // 4
};
//Union variable
int main() { //g++
// void main() { //gcc
struct type1 a;
struct type2 b;
printf( "size of type1 : %d \n", sizeof(a) );
printf( "size of type2 : %d \n", sizeof(b) );
union utype1 x;
union utype2 y;
printf( "size of utype1 : %d \n", sizeof(x) );
printf( "size of utype2 : %d \n", sizeof(y) );
/*
default align (4) bytes (word) :
size of type1 : 12
size of type2 : 8
size of utype1 : 4
size of utype2 : 4
no align :
size of type1 : 7
size of type2 : 7
size of utype1 : 4
size of utype2 : 4
*/
}
如果没有指定,会自动对齐。而且内容的排列会影响大小。
如果指定了,会根据指定的 byte 对齐。pragma pack(1) // no alignment
内容排列没有影响到 共用体内存长度 。