简体   繁体   English

数组与 C 编程语言中的结构和联合有何不同?

[英]How Array is different from Structures and Unions in C programming Language?

I am unable to understand difference between them.我无法理解它们之间的区别。 When the same thing is done by three of them then when we should go for Array/Structure/Union?当他们三个人做同样的事情时,我们什么时候应该选择 Array/Structure/Union?

In an array all the elements have the same size and type, so you can't use one for an int and the other one as a double value, and so on.在数组中,所有元素都具有相同的大小和类型,因此您不能将一个用于int将另一个用作double值,依此类推。

In struct s, every element can have a different size or type.struct ,每个元素都可以有不同的大小或类型。 You can use one as an int and the others for any data type you can use for a regular variable, you can also have arrays of structures.您可以将一个用作int ,将其他用作可用于常规变量的任何数据类型,您也可以拥有结构数组。

The union s are used to use a single variable for possibly multiple data types. union用于将单个变量用于可能的多种数据类型。 In a union the size of an instance equals the size of it's largest member, unlike in struct s where it equals the sum of individual member sizes.union中,实例的大小等于其最大成员的大小,这与struct s 中它等于单个成员大小的总和不同。

Also, essentially the syntax is very much clearer if you use a struct even for members of the same type.此外,如果您使用struct即使对于相同类型的成员,本质上语法也会更加清晰。 For example, instead of having例如,而不是拥有

float ****point3d;

You could have你可以有

struct point3d_s {
    float x, float y, float z;
};
point3d_s *point3d;

will declare a pointer to a 3 dimensional point, which in turn can be used as an array too.将声明一个指向 3 维点的指针,该点又可以用作数组。

Well, they are three totally different objects.好吧,它们是三个完全不同的对象。

Use array when you should have many (well, at least two...) elements of the very same type.当您应该有许多(至少两个...)相同类型的元素时,请使用数组 Mainly, when the number of them might vary.主要是,当它们的数量可能会有所不同时。 For example: Hold all the phone numbers of students in a class.例如:保存一个班级所有学生的电话号码。

Use struct when you should aggregate a few variables together.当您应该将几个变量聚合在一起时,请使用struct For example: Hold, per a student, their name, their phone number and their address.例如: 为每个学生保留他们的姓名、电话号码和地址。

Use union when you should always use only one variable type out of a few possible ones.当您应该始终只使用几种可能的变量类型中的一种时,请使用union For example: Hold, per a student, either his phone number or their email address.例如:保持,每一个学生,无论是他的电话号码电子邮件地址。

Array has no padding in between its elements as compared to structure.与结构相比,数组在其元素之间没有填充。 All elements of array and structure are considered for total size calculation, while union size is equal to its maximum sized element.计算总大小时考虑数组和结构的所有元素,而联合大小等于其最大大小的元素。

Array have all elements of same type, which is no prerequisite for structure and union.数组具有相同类型的所有元素,这不是结构和联合的先决条件。

Array uses index based access for accessing its elements, while structure and union uses .element_name for accessing its elements.数组使用基于索引的访问来访问其元素,而结构和联合使用.element_name来访问其元素。

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

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