Preview
Introduction to Structure in C
Structure is a user defined data type which is a collection of different variables of different types.
Syntax for structure is:
struct <struct_name>
{
<type1> var1;
<type2> var2;
:
:
<typeN> var-N;
};
struct is the keyword specifying the beginnning of structure.
struct_name is the name of structure. which should follow rules of a valid identifier of C language.
{ Opening brace specifies that structure has started.
type1, type2,… typeN refer to different data types.
var1, var2,… var-N are variables declared inside the structure. They are also called structure members .
} Closing brace specifies that structure has ended.
; Semicolon should be written after closing brace.
Example
struct data
{
int a;
float b;
};
In the above example, structure named data has been defined which contains two elements named a and b.
Declaration of a Structure variable
Variables of a structure can be declared just like variables of other data types.
To declare a variable of structure , struct keyword followed by name of structure followed by structure type variables should be written
Syntax for declaring a structure variable is:
struct <struct_name> v1,v2,…..vN;
v1,v2,……..vN are structure variables.
Example:
struct data d;
In the above example, variable d has been declared for already declared structure data.
Accessing structure members
Dot (.) operator or arrow operator -> can be used to put or access values structure elements through a structure variable.
The syntax:
structvar.member_name;
or
structvar->member_name;
Here, structvar is the name of structure variable and member_name is the element of structure.
Program |
#include<stdio.h> struct data { int a; float b; }; int main() { struct data d; d.a=13; d.b=20.55; printf(“\nd.a=%d”,d.a); printf(“\nd.b=%f”,d.b); return(0); } |
Output |
d.a=13 d.b=20.549999 |
Description |
In the above program, structure variable d contains 13 for its first element a and 20.55 for its second element b. |
Initialization of a structure variable
We can initialize a structure variable by putting values within the pair of braces. These values are assigned to the structure elements on one to one basis
Syntax:
struct <structname><var>={List};
Example:
struct data
{
int a;
float b;
};
struct data d={20,50.5};
In this example, structure variable d has been initialized with values 20,50.5. 20 would be stored in d.a and 50.5 would be stored in d.b .
Program |
#include<stdio.h> struct data { int a; float b; }; int main() { struct data d={3,7.8}; printf(“\nd.a=%d”,d.a); printf(“\nd.b=%f”,d.b); return(0); } |
Output |
d.a=3 d.b=7.800000 |
Description |
In the above program, structure variable d has been initialized to contain 3 for its first element a and 7.8 for its second element b. |
Best Sellers