Using structures, you can define your own data type which can store multiple dissimilar primitive data types. Actually this type of data types is called user defined data types. For example, you can represent any real life object properties like student –
- roll number – integer
- name – character array
- class – integer
- section – character
- last year marks in percentile – float
- school name – character array
Here you can see that there are different data types which represent a particular student. So, using structure you can do this very easily in C.
Structure Declarations
In C, to define a structure there is a keyword “struct” is used. The syntax of the statement is like below.
struct { member_name; member_name; member_name; ... } <one or more structure variables>;
For example, the above mentioned student declaration would be like this
struct student { int roll_number; char name[50]; int class; char section; float marks; char school_name[50]; } student_1;
Here, student_1 is the structure variable. You can also declare structure variable like below:
struct student student_2;
There is another good way to declare structure and its variables, using typedef keyword. The typedef keyword, actually defines a new data type by which you can use a data type the same way like other primitive data types.
typedef struct student { int roll_number; char name[50]; int class; char section; float marks; char school_name[50]; } student;
Here, using typedef we are defining a new data type called student. Now we can use this data type just like any other data types we know like int float etc. for variable declarations.
student student_1,student_2;
You can also initialize the structure variables also to zero like this:
student student_1 = {0};
No comments:
Post a Comment