简体   繁体   English

相同数据类型的结构和数组之间有什么区别?

[英]What is the difference between a struct of the same datatype and an array?

If I had a struct consisting only of short unsigned integers, that would be stored in contiguous memory locations of the same size; 如果我有一个仅包含短无符号整数的结构,它将存储在相同大小的连续内存位置中; the same also applies if I have an array of short unsigned integers. 如果我有一个短无符号整数数组,则同样适用。 How would they be any different? 它们会有什么不同? Is it how they are accessed? 是如何访问它们的? I am aware that an array is accessed by using a pointer to reference the starting value of the array while an array operator sets an offset from that memory location, does the same apply to structs or are structs accessed by using the memory location for each piece of data? 我知道数组是通过使用指针引用数组的起始值来访问的,而数组运算符设置了与该内存位置的偏移量,是否对结构体也是如此,还是通过使用每块内存位置来访问结构体数据的?

No, they need not be the same and most likely, they are not. 不,它们不必相同,而且很可能不是。

In case of structure members, there can be padding between the members. 对于结构构件,构件之间可能会有填充物。 So, it is not guaranteed that consecutive members will reside in contiguous memory. 因此,不能保证连续的成员将驻留在连续的内存中。 In this case, based on implementation, pointer arithmetic using the address of the first element may or may not 在这种情况下,根据实现,使用或不使用第一元素地址的指针算法 work 工作 be valid. 有效。

Quoting relevant parts of C11 standard, chapter §6.7.2.1/p15, Structure and union specifiers, 引用C11标准的相关部分,第6.7.2.1/p15章,结构和联合说明符,

[..] There may be unnamed padding within a structure object, but not at its beginning. [..]结构对象中可能有未命名的填充,但在其开始处没有。

and

chapter §6.5.3.4, sizeof operator, 第6.5.3.4节, sizeof运算符,

[...] When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding. [...]当应用于具有结构或联合类型的操作数时,结果是此类对象中的字节总数,包括内部填充和结尾填充。

In case of an array, however, all members are guaranteed to reside in contiguous memory and pointer arithmetic is deterministic. 但是,在数组的情况下,保证所有成员都驻留在连续的内存中,并且指针算法是确定性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM