众所周知,结构的内存是在定义其变量时(或创建实例时)分配的。
现在
struct Programmer {
int skills;
int problemSolved;
};
int main(){
Programmer me;//Here the memory will be allocated but in what
//format(discrete or continuous block of memory)?
me.skills = 10;
me.problemSolved = 2000;
return 0;
}
分配给结构实例或变量的内存是连续 block (如数组)还是离散内存块?如果是,那为什么?
最佳答案
为struct
分配的内存是连续的。来自 §6.2.5 ¶20 C11 标准草案:
A structure type describes a sequentially allocated nonempty set of member objects....
但是,根据 §6.7.2.1 ¶15,为 struct
分配的存储空间中可能存在填充。 :
There may be unnamed padding within a structure object, but not at its beginning.
并且,来自 6.7.2.1 ¶17 :
There may be unnamed padding at the end of a structure or union.
关于c++ - c++中的结构内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45557092/