Vasudha Dixit Vasudha Dixit - 11 months ago 57
C Question

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?

Answer Source

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 float value, and so on.

In structs, every element can have a different size or type. 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.

The unions are used to use a single variable for possibly multiple data types. In a union the size of an instance equals the size of it's largest member, unlike in structs where it equals the sum of individual member sizes.

Also, essentially the syntax is very much clearer if you use a struct even for members of the same type. 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.

I don't mean that arrays are useless, but I guess you can infer what I mean without further explanation.