带有数组的C结构的内存布局 [英] Memory layout of C struct with arrays

查看:69
本文介绍了带有数组的C结构的内存布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的C结构定义如下:

Suppose I have a C struct defined as follows:

typedef struct 
{
  double array1[2];
} struct0_T;

内存的布置方式如何? struct是仅保留一个指针还是两个双精度值?在我以为该结构拥有一个指针之前,但是今天我(令我惊讶)发现这些值存储在这里.不同的编译器之间会有所不同吗?

How is the memory laid out? Is struct going to hold just a pointer or the value of the two doubles? Before I thought the struct holds a pointer, but today I found out (to my surprise) that the values are stored there. Does it vary between different compilers?

推荐答案

该结构包含两个值.内存布局为.array1[0],后跟.array1[1],然后可选地加上一些填充.

The struct contains the two values. The memory layout is .array1[0], followed by .array1[1], optionally followed by some amount of padding.

填充是其中唯一可以在编译器之间变化的部分(尽管在实践中,结构的唯一成员是数组,几乎可以肯定没有填充).

The padding is the only part that of this that can vary between compilers (although in practice, with the only member of the struct being an array there will almost certainly be no padding).

尽管您可能已经听说C中的数组是一个指针,但事实并非如此-数组是由所有成员对象组成的聚合类型,就像struct一样.仅仅是在几乎所有的表达式上下文中,数组都会求出指向其第一个成员的指针.

Although you may have heard that an array in C is a pointer, that is not true - an array is an aggregate type consisting of all the member objects, just like a struct. It is just that in almost all expression contexts, an array evaluates to a pointer to its first member.

这篇关于带有数组的C结构的内存布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆