C Program Learning Part-10 - Engineer Simple

Search This Blog

C Program Learning Part-10

 Structures and Unions



C Structures 

Structure is a user-defined data type in C language which allows us to combine data of different types together. Structure helps to construct a complex data type which is more meaningful. It is somewhat similar to an Array, but an array holds data of similar type only. But structure on the other hand, can store data of any type, which is practical more useful.
How to define structures? 
Before you can create structure variables, you need to define its data type. To define a struct, the struct keyword is used.


Syntax of struct 

struct structureName 
dataType member1; 
dataType member2; 
... 
};

Here is an example: 
struct Person 
char name[50]; 
int citNo; 
float salary; 
}; 

Difference between Structure and Array


ARRAY

STRUCTURE

Array refers to a collection consisting of elements of homogenous data type.

Structure refers to a collection consisting of elements of heterogenous data type.

Array uses subscripts or “[ ]” (square bracket) for element access

Structure uses “.” (Dot operator) for element access

Array size is fixed and is basically the number of elements multiplied by the size of an element

Structure size is not fixed as each element of Structure can be of different type and size.

Array declaration is done simply using [] and not any keyword.

Structure declaration is done with the help of “struct” keyword.

Arrays is a primitive datatype

Structure is a user-defined datatype.

Array traversal and searching is easy and fast.

Structure traversal and searching is complex and slow.

data_type array_name[size];

struct sruct_name{

data_type1 ele1;

data_type2 ele2;

};

Array elements are stored in continuous memory locations.

Structure elements may or may not be stored in a continuous memory location.



Differences Between Stricture and Union



C – Typedef 

Typedef is a keyword that is used to give a new symbolic name for the existing name in a C program. This is same like defining alias for the commands. 
Consider the below structure. 
typedef struct student
int mark [2]; 
char name [10]; 
float average; 
} status;
To declare structure variable, we can use the below statements. 
status record1;            /* record 1 is structure variable */ 
status record2;           /* record 2 is structure variable */


To get our all parts of C Program-


Next Post Previous Post
No Comment
Add Comment
comment url