Structure In C - Fundamentals
Tags: beginners, tutorial, c, structure
Published: 2020-08-20 13:40:47

📸*<span> by <a href="https://unsplash.com/@mybbor?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Robby McCullough</a> on <a href="https://unsplash.com/s/photos/structure?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>*

We have variables of different data types such as `int`s, `char`s, `float`s, etc to store data. We have arrays to group together a collection of data of the same data type.

But in reality, we will not always have the luxury of having data of one type. That's where a **structure** comes into the picture.

---

###Topics-

0.[ Definition and Declaration](#defdec)
1.[ Initialization and Accessing the Members of a Structure](#init)
2.[ Operating with Structure Variable](#operating)
3.[ Array Of Structure](#array)
4.[ Nested Structure](#nest)

---

###0. Definition and Declaration<a name="defdec"></a>

A structure is a **collection** of one or more variables, possibly of different types, grouped under a single name. It is a **user-defined** data type. They help to organize complicated data in large programs, as they allow a group of logically related variables to be treated as one.

For example, a student can have properties name, age, gender and marks. We could create a `char`acter array for `name`, an `int`eger variable for `roll`, a `char`acter variable for gender and an `int`eger array for `marks`. But if there are 20 or 100 students, it will be difficult to handle those variables.

We can declare a structure using `struct` keyword following the syntax as below:

```c
struct structureName
        {
            dataType memberVariable1;
            datatype memberVariable2;
            ...
        };

 /* Example */
struct student
    {
        char name[20];
        int roll;
        char gender;
        int marks[5];
    };
```

The above statement defines a new data type `struct student`. Each variable of this data type will consist of `name[20]`, `roll`, `gender` and `marks[5]`. These are known as **members** of the structure.

Once a structure is declared as a new data type, then the variables of that data type can be created.

```c

 /* Variable declaration */
struct structureName structureVariable;

 /* Example /*
struct student stu1;
struct student stu2,stu3,stu4;
```

Each variable of `struct student` has its copies of the members.

**Few important nuggets-**

1. The members of the structure do not occupy memory until a structure variable is created.

2. You might have noticed we are using `struct` while variable declaration as well. Isn't that tedious? 

Using the `typedef` keyword in the structure declaration we can prevent writing `struct` again.

```c
typedef struct students
    {
        char name[20];
        int roll;
        char gender;
        int marks[5];
    } STUDENT; 

/* or */
typedef struct
    {
        char name[20];
        int roll;
        char gender;
        int marks[5];
    } STUDENT; 


STUDENT stu1,stu2,stu3,stu4;
```

By convention, **uppercase** letters are used for *type definitions* ( such as `STUDENT`).

3.The structure definition and variable declaration can be combined as below.

```c
struct student
    {
        char name[20];
        int roll;
        chat gender;
        int marks[5];
    }stu1, stu2, stu3, stu4;
```

4.The use of `structureName` is optional. The code below is completely valid.

```c
struct
    {
        char name[20];
        int roll;
        char gender;
        int marks[5];
    }stu1, stu2, stu3, stu4;
```

5.Structures are generally declared at the top of the source code file, even before defining functions.

6.C doesn't allow variable initialization inside a structure declaration.

###1. Initialization and Accessing the Members of a Structure<a name = "init"></a>

Like any other variable, a structure variable can also be initialized where they are declared. There is a one-to-one relationship between the members and their initializing values.

```c
 /* Variable Initialization */
struct structureName = { value1, value2,...};

 /* Example */
typedef struct
    {
        char name[20];
        int roll;
        char gender;
        int marks[5];
    }STUDENT;

void main(){
STUDENT stu1 = { "Alex", 43, 'M', {76, 78, 56, 98, 92}};
STUDENT stu2 = { "Max", 33, 'M', {87, 84, 82, 96, 78}};
}
```

To access the members, we have to use `.` ( **dot operator**).

```c
 /* Accessing Memebers of a Structure */
structureVariable.memberVariable

/* Example */
 printf("Name: %s\n", stu1.name);
 printf("Roll: %d\n", stu1.roll);
 printf("Gender: %c\n", stu1.gender);
 for( int i = 0; i < 5; i++)
   printf("Marks in %dth subject: %d\n", i, stu1.marks[i]);

/* Output */
Name: Alex
Roll: 43
Gender: M
Marks in 0th subject: 76
Marks in 1th subject: 78
Marks in 2th subject: 56
Marks in 3th subject: 98
Marks in 4th subject: 92
```

The members can be initialized in the variable declaration in any order using `.`.

```c
STUDENT stu3 = { .gender = 'M', .roll = 23, .name = "Gasly", .marks = { 99, 45, 67, 78, 94}};
```

We can also initialize the first few members and leave the remaining blank. However, the uninitialized members should be **only** at the end of the list.

Uninitialized `int`egers and floating-point numbers have a default value `0`. It is `\0`( NULL) for `char`acters and strings.

```c
STUDENT stu4 = { "Kviyat", 65};
 /* same as { "Kviyat", 65, '\0', { 0, 0, 0, 0, 0} } */
```   

###2. Operating with Structure Variable<a name = "operating"></a>

Like variables of primitive data types, we cannot perform arithmetic operations such as `+`, `-`, `*`, `/`, etc. Likewise, relational and equality operators cannot be used with structure variables. But, we can copy one structure variable to another, provided they belong to the same structure. 

```c
 /* Invalid Operations */
stu1 + stu2
stu1 - stu2
stu1 == stu2
stu1 != stu2 etc.

 /* Valid Operation */
stu1 = stu2
```

We will have to compare the structure members individually to compare structure variables.

```c
#include <stdio.h>
#include <string.h>

 struct student
    {
        char name[20];
        double roll;
        char gender;
        int marks[5];
    }stu1,stu2;


void main()
{
    struct student stu1= { "Alex", 43, 'M', {76, 78, 56, 98, 92}};
    struct student stu2 = { "Max", 33, 'M', {87, 84, 82, 96, 78}};

    if( strcmp(stu1.name,stu2.name) == 0 && stu1.roll == stu2.roll)
        printf("Both are the records of the same student.\n");
    else printf("Different records, different students.\n");

     /* Copiying the structure variable */
    st2 = st1;

    if( strcmp(stu1.name,stu2.name) == 0 && stu1.roll == stu2.roll)
        printf("\nBoth are the records of the same student.\n");
    else printf("\nDifferent records, different students.\n");
}

 /* Output */
Different records, different students.

Both are the records of the same student.

```

###3. Array of Structure<a name="array"></a>

You have already seen how we had to create 4 different `struct student` type variables to store the records of 4 students. A better way would be to create an array of `struct student` ( just like array of `int`s).

```c
struct student
    {
        char name[20];
        double roll;
        char gender;
        int marks[5];
    };

struct student stu[4];
```

To access the elements of the array `stu` and the members of each element, loops can be used.

```c
 /* Taking values for the user */

for(int i = 0; i < 4; i++)
    {
        printf("Enter name:\n");
        scanf("%s",&stu[i].name);
        printf("Enter roll:\n");
        scanf("%d",&stu[i].roll);
        printf("Enter gender:\n");
        scanf(" %c",&stu[i].gender);

        for( int j = 0; j < 5; j++)
        {
            printf("Enter marks of %dth subject:\n",j);
            scanf("%d",&stu[i].marks[j]);
        }

        printf("\n-------------------\n\n");
    }

 /* Finding the average marks and printing it */

for(int i = 0; i < 4; i++)
    {
        float sum = 0;
        for( int j = 0; j < 5; j++)
        {
            sum += stu[i].marks[j];
        }

        printf("Name: %s\nAverage Marks = %.2f\n\n", stu[i].name,sum/5);
    }
```

###4. Nested Structure<a name="nest"></a>

Nesting of structure means having one or more structure variables inside another structure. Like we declare an `int` member or `char` member, we can also declare a structure variable as a member.

```c
struct date
    {
       int date;
       int month;
       int year;
    };

struct student
    {
        char name[20];
        int roll;
        char gender;
        int marks[5];
        struct birth birthday;
    };

void main(){
 struct student stu1;
```

The structure variable `birthday` of type `struct birth` is nested inside `struct student`. It is quite apparent you cannot nest a structure variable of type `struct student` inside `struct student`.

Note that the structure to be nested has to be declared first. Using `.`, we can access the members contained within the inner structure as well as other members.

```c
 /* Example */
stu1.birthday.date
stu1.birthday.month
stu1.birthday.year
stu1.name
```

Structure variables of different types can be nested as well.

```c
struct birth
    {
       int date;
       int month;
       int year;
    };
    
struct relation
    {
        char fathersName[20];
        char mothersName[20];
    };

struct student
    {
        char name[20];
        int roll;
        char gender;
        int marks[5];
        struct birth birthday;
        struct relation parents; 
    };
```
---

In the second one, we will discuss the memory allocation of structure and their relationship with pointers and functions.