LERAN C PROGRAMMING

Learn one of the most powerful programming languages in the world and become a rockstar developer.

Structures


In this tutorial, you'll learn about struct types in C Programming. You will learn to define and use structures with the help of examples.

In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name.


How to define structures?

Before you can create structure variables, you need to define its data type. To define a struct, the struct keyword is used.

struct structureName 
{
    dataType member1;
    dataType member2;
    ...
};

Structure can be declared using struct keyword.
Members of the structure must be enclosed between curly brackets and declaration of structure must end with semicolon.

Here is an example:

struct Person
{
    char name[50];
    int citNo;
    float salary;
};

Here, a derived type struct Person is defined. Now, you can create variables of this type.

How To Declare Structure Variable

Once structure is declared we can declare variables of type structure.

There are two different methods of declaring structure variables.

Method1: Declare Structure variables at the time of declaring structure.

Here is and SYNTAX:

struct structure_name 
{
   datatype variable1;
   datatype variable2;
   ..................
   datatype variableN;
}var1,var2,var3;

In above method structure variables are declared just after the definition of structure

EXAMPLE:

struct Student
{
    int rollno;
    char name[20];
    char city[20];
}S1,S2,S3;

Memory allocation for the members of the structure is done at the time of declaring structure variables. Memeory is allocated Separately for each structure variables. Total memory occupied by structure variable depends on the data type of structure members.

Here,

Member Name Data Type Size in Byte
rollno int 2
name char 20
city char 20
Total Memory Occupied 42

So 42 Bytes of memory is allocated to each structure variables S1, S2 and S3.

How To Access Member of Structure

Data Members of the structure can be accessed using name of structure variable followed by dot (.) operator and then followed by member name.

SYNTAX:

structure_variable_name.member_name;

EXAMPLE:

S1.rollno=1;
S1.name="SURESH";
S1.city="Kathmandu";


Previous Next
x
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Privacy Policy That's Fine