可能重复:
C++:空类对象的大小是多少?
为什么以下输出1
?
#include <iostream>
class Test
{
};
int main()
{
std::cout << sizeof(Test);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我有两个结构定义如下:
struct EmptyStruct{
};
struct StructEmptyArr{
int arr[0];
};
int main(void){
printf("sizeof(EmptyStruct) = %ld\n", sizeof(EmptyStruct));
printf("sizeof(StructEmptyArr) = %ld\n", sizeof(StructEmptyArr));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在Ubuntu 14.04,x64上用gcc(g ++)4.8.4编译.
输出(对于gcc和g ++):
sizeof(EmptyStruct) = 1
sizeof(StructEmptyArr) = 0
Run Code Online (Sandbox Code Playgroud)
我能理解为什么sizeof(EmptyStruct)
等于1
但不能理解为什么sizeof(StructEmptyArr)
等于0
.为什么两者之间存在差异?
可能重复:
C++中的空类C
中空结构的大小是多少?
我在某处看到C++中空结构的大小为1.所以我想到验证它.不幸的是我把它保存为C文件并使用了<stdio.h>
标题,我很惊讶地看到了输出.这是0.
这意味着
struct Empty {
};
int main(void)
{
printf("%d",(int)sizeof(Empty));
}
Run Code Online (Sandbox Code Playgroud)
在编译为C文件时打印0,在编译为C++文件时打印1.我想知道原因.我读到c ++中的sizeof空结构不为零,因为如果大小为0,则该类的两个对象将具有相同的地址,这是不可能的.我哪里错了?
给定的C代码
#include <stdio.h>
int x = 14;
size_t check()
{
struct x {};
return sizeof(x); // which x
}
int main()
{
printf("%zu",check());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我的32位实现上给出4作为C的输出,而在C++中给出代码
#include <iostream>
int x = 14;
size_t check()
{
struct x {};
return sizeof(x); // which x
}
int main()
{
std::cout<< check();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出1.为何如此差异?
struct t_empty {
};
Run Code Online (Sandbox Code Playgroud)
这似乎可以在C++中正确编译,但不能在C中编译.(至少使用TI 28xx DSP编译器,它会发出错误"预期声明")这是在C标准的某处提到的,还是我的编译器坏了?
以下行打印输出为4,而我期待0.
printk(KERN_INFO "size of spinlock_t %d\n", sizeof(spinlock_t));
Run Code Online (Sandbox Code Playgroud)
我在一个单CPU的系统上试过这个.构建内核时没有启用调试标志CONFIG_DEBUG_SPINLOCK or CONFIG_DEBUG_LOCK_ALLOC
.根据内核头文件,它应该为零,但输出与它不一致,任何猜测?
虽然在这里引用内核代码,但是struct page;
没有成员定义(我猜这不是前向声明).
但是这篇文章中接受的答案是不允许的.
然后我试了一个样本,
#include <stdio.h>
struct page;
struct arm_vmregion
{
unsigned long vm_start;
unsigned long vm_end;
struct page *vm_pages;
int vm_active;
const void *caller;
};
int main()
{
struct arm_vmregion aa;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它编译成功
empty_struct.c: In function ‘main’:
empty_struct.c:15:22: warning: unused variable ‘aa’ [-Wunused-variable]
Run Code Online (Sandbox Code Playgroud)
请在这方面澄清一下.