C Structure

C Structure:

Among other data types like int, array, string, etc, C facilitates a very unique data type that can hold elements of different data types in a single variable and thus is often called as an user-defined data type.

Any information about a person, class or product, etc. is best stored in a structure where each element is often called as a member of a structure.

Syntax:

{

data_type element 1;

data_type element 2;

.

.

data_type element N;

};

Declaring a Structure Variable:

●      Using struct keyword:

Structure variable can be declared by using struct keyword within the main function. This way of declaration provides a flexibility of multiple declaration. Thus it is best preferred, if no. of variables varies.

●       At the time of defining structure:

Structure variable can also be declared at the time of defining structure. This way of declaration decreases the number of coe lines. Thus it is best preferred, if no. of variables are fixed.

Accessing a Structure Member:

To access a structure member, either use a member or a dot operator (.) or a structure pointer operator (->).

Example:

#include<stdio.h>  
#include <string.h>
 
struct student 	 
{   
int roll_no; 	 
char name[30]; 	 
}s;  
 
void main( )    
{    
 
s.roll_no = 1;    
strcpy(s.name, "Jai");
 
printf( "Student Enrollment No. : %d\n", s.roll_no);    
printf( "Student Name : %s\n", s.name);    
}

Output

Student Enrollment No. : 1
Student Name : Jai
Please follow and like us:
Content Protection by DMCA.com