c - Does a C struct hold its members in a contiguous block of memory?
问题描述
Let's say my code is:
typedef stuct {
int x;
double y;
char z;
} Foo;
would x
, y
, and z
, be right next to each other in memory? Could pointer arithmetic 'iterate' over them?
My C is rusty so I can not quite get the program right to test this.
Here is my code in full.
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int x;
double y;
char z;
} Foo;
int main() {
Foo *f = malloc(sizeof(Foo));
f->x = 10;
f->y = 30.0;
f->z = 'c';
// Pointer to iterate.
for(int i = 0; i == sizeof(Foo); i++) {
if (i == 0) {
printf(*(f + i));
}
else if (i == (sizeof(int) + 1)) {
printf(*(f + i));
}
else if (i ==(sizeof(int) + sizeof(double) + 1)) {
printf(*(f + i));
}
else {
continue;
}
return 0;
}
解决方案
No, it is not guaranteed for struct
members to be contiguous in memory.
From §6.7.2.1 point 15 in the C standard (page 115 here):
There may be unnamed padding within a structure object, but not at its beginning.
Most of the times, something like:
struct mystruct {
int a;
char b;
int c;
};
Is indeed aligned to sizeof(int)
, like this:
0 1 2 3 4 5 6 7 8 9 10 11
[a ][b][padding][c ]
推荐阅读
- python - 在二维数组的每一行前面添加文本
- javascript - ngfor嵌套标签id根据项目计数递增递减
- c# - 试图从系统托盘中获取列表应用程序
- clojure - 如何在clojure中使用etaoin做一个涉及shadowDom的querySelector
- python - 如何使 Django 模型字段从另一个字段派生其值并且不可编辑
- python - 在带有 SP1 的 Windows 7 32 位上安装 Python 3.8
- react-native - 仅将 backgroundColor 和高度/阴影应用于 FlatList 的项目容器(不包括标题)
- mongodb - 无法在 kubernetes pod 上创建 mongodb 副本集
- plot - 基础 r 图中的轴不均匀
- arrays - 通过在数组上减少创建字典与在迭代中分配每个项目之间的区别