STRUCTURES

The keyword struct is used to create structures in C. Structures are quite similar to arrays. It is a collection of variables that can be of different type defined under a single name.

Syntax :

struct structure_name
{
Data type element1;
Data type element2;
Data type element3;
……..
……..
};

 

Example :

struct profile
{
char studentname[ ];
int marks;
float percentage;
};

 

Creating struct variable

We need to create variables in order to allocate memory storage for a given structure type and work on it.

Example to show how struct variables are created in C :

#include <stdio.h>
struct profile
{
char studentname[ ];
int marks;
float percentage;
};

int main( )
{
struct profile student1, student2, s[10];
return 0;
}

 

You can also use the following method to create struct variable :

#include <stdio.h>

struct profile
{
char studentname[ ];
int marks;
float percentage;
} student1, student2, s[10];

In the above mentioned examples, the variables student1 and student2 are created along with an array variable s having 10 elements of type struct pofile.

 

Operators to access members of structure

With the help of following mentioned operators you can access the members of structure :
Member Operator (.) : To access a particular member of structure.

Example

#include <stdio.h>
struct profile
{
char studentname[ ];
int marks;
float percentage;
};

int main( )
{
struct profile student1, student2, s[10];
student1.studentname;
student1.marks;
student.percentage;
return 0;
}

Structure Pointer Operator ( ->) : Using the pointer along with the operator (->) you can access members of structure.

Example

#include <stdio.h>
struct profile
{
char studentname[ ];
int marks;
float percentage;
};

int main( )
{
struct profile *profilePtr, student1;
profilePtr = &student1;

printf( “Enter name:” );
scanf( “ %s ” , &profilePtr -> studentname );

printf( “ Enter marks:” );
scanf ( “ %d ” , &profilePtr -> marks);

printf( “ Enter percentage:” );
scanf ( “ %f ” , &profilePtr -> percentage);
return 0;
}

WHAT IS NESTED STRUCTURE? 

A structure in C within another structure is known as nested structure.

Example :
struct integer
{
int positive;
int negative;
};
struct number
{
struct integer comp;
int values;
} n1 , n2;

 

Use of typedef in C:

The typedef is used in C structure to reduce the code. It increases the readability and reduces the complexity of the program.

Example :

typedef struct info

{

char *student;

char *college;

char *course;

} addr;

…..

…..

addr i;

i.course = “Btech”;

Leave a Reply

Your email address will not be published. Required fields are marked *