📜  C中数组和联合的区别

📅  最后修改于: 2021-09-12 11:27:34             🧑  作者: Mango

1. C 中的数组:
数组是由存储在连续内存位置的通用名称访问的相似数据项的集合。可以使用索引访问数组的元素。它们可用于存储原始数据类型,例如 int、float、double、char 等,但所有元素必须具有相同的数据类型。下面是数组的如画表示。

数组声明:

datatype array_name[size]

2. C 中的联合:
Union 是一种用户定义的数据类型,允许在同一内存位置存储异构元素。联合的大小是联合中最大元素的大小。下面是一个工会的风景如画的表示。

联合声明:

union name
{
  datatype element;
  datatype element;
};

数组和联合之间的区别:

ARRAY UNION
Collection of elements of same data types. Collection of elements of heterogenous data types.
Arrays can be one or two dimensional. Unions do not have type.
Each element is allocated a specific memory location. The elements share the memory location which has size equivalent to the size of the largest size element of the union.
All members can contain value at a given time. Only one member can contain value at a given time.
Not an efficient use of memory as all members are allocated different memory locations. Efficient use of memory as all members do not require separate memory location.
Array elements can be accessed using index. The elements of a union cannot be accessed using index.

Syntax :

datatype array_name[size]

Syntax :
Union user defined name

{

datatype Variable 1; datatype variable2;

};

想要从精选的视频和练习题中学习,请查看 C 基础到高级C 基础课程。