c++ - c++中的结构内存分配

标签 c++ c memory structure instance

众所周知,结构的内存是在定义其变量时(或创建实例时)分配的。

现在

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/

相关文章:

c++ - 使用 PugiXML 进行 XML 解析,无限循环

c++ - 使用映射参数的转换构造函数给出错误

c - Sscanf 没有返回我想要的

c++ - 奇怪的语法:范围运算符 (::) 后的星号?

c++ - 移出的 xvalue 究竟需要什么?

c++ - 构建用于发布的卷影服务应用程序

c - 帮助在 Xcode 上用 C 语言打开文件

C++:缓存 JSON 而不是对象会减少内存消耗吗?

c++ - shmget shmat 无法正常工作

c# - 从内存中清除 C# 字符串