Topic: Data Structures in C
Data Structure (Struct)
Many times it is necessary to group information of different data types. Arrays require that all elements be of the same data type. An example is a information about student. The information typically includes a name (char Array) , a ID number(int type), Marks (float type), average (float type). Often multiple variables must be passed from one function to another; these variables have different data types. Thus it is useful to have a container to store various types of variables in. Structs allow the programmer to do just that.
A struct is a derived data type composed of members that are each fundamental or derived data types. A single struct would store the data for one object. A struct can be defined in several ways as illustrated in the following examples:
The fundamental data types int, float, char are predefined by the compiler. This is not true for structures as it contains many elements of different data types. Each variable of S1& S2 will contain three members:
int id;
float marks[5];
char name[20];
And if we consider example Below:
struct student
{
int id;
float marks[5];
char name[20];
} ;
This doesn’t create any new variable so doesn’t set aside any storage in memory. It just tells the compiler what the data type struct student looks like. The name student is called the Tag. This is not a variable, it is type name. The members are surrounded by braces.
The name tag is not a variable name but it is type tag. Struct s1 and s2 set aside memory space.
struct student
{
int id;
float marks[5];
char name[20];
} ;
Struct student s1,s2;
Accessing Struct Members
How individual element of an array is access? Individual members of a struct variable may be accessed using the structure member operator (the dot, “.”)
s1.id=2 ;
s1.n=‘C’;
The name preceding the dot is structure name and the name following, it is the specific members of the structure. For accessing the structure members
Printf(“%d”,s1.id)
Printf(“%c”,s1.n)
The dot operator (.) connects a structure variable with a member of the structure.
Combining Deceleration
You can combine in one statement the declaration of the structure type and the definition of the structure variables.
struct student
{
int id;
float marks[5];
char name[20];
} student s1,s2;
Example
Course is Continued.........
Plz See Lec No: 07
No comments:
Post a Comment