Skip to content

Exercises En C Structures Assignment

PrevNext

C Structure is a collection of different data types which are grouped together and each element in a C structure is called member.

  • If you want to access structure members in C, structure variable should be declared.
  • Many structure variables can be declared for same structure and memory will be allocated for each separately.
  • It is a best practice to initialize a structure to null while declaring, if we don’t assign any values to structure members.

Difference between C variable, C array and C structure:

  • A normal C variable can hold only one data of one data type at a time.
  • An array can hold group of data of same data type.
  • A structure can hold group of data of different data types and Data types can be int, char, float, double and long double etc.

C Structure:

Syntaxstruct student
{
int a;
char b[10];
}
Examplea = 10;
b = “Hello”;

C Variable:

intSyntax: int a;
Example: a = 20;
charSyntax: char b;
Example: b=’Z’;

C Array:

intSyntax: int a[3];
Example:
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = ‘\0’;
charSyntax: char b[10];
Example:
b=”Hello”;

Below table explains following concepts in C structure.

  1. How to declare a C structure?
  2. How to initialize a C structure?
  3. How to access the members of a C structure?
Using normal variableUsing pointer variable
Syntax:
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Syntax:
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example:
struct student
{
int  mark;
char name[10];
float average;
};
Example:
struct student
{
int  mark;
char name[10];
float average;
};
Declaring structure using normal variable:
struct student report;
Declaring structure using pointer variable:
struct student *report, rep;
Initializing structure using normal variable:
struct student report = {100, “Mani”, 99.5};
Initializing structure using pointer variable:
struct student rep = {100, “Mani”, 99.5};
report = &rep;
Accessing structure members using normal variable:
report.mark;
report.name;
report.average;
Accessing structure members using pointer variable:
report  -> mark;
report -> name;
report -> average;

Example program for C structure:

This program is used to store and access “id, name and percentage” for one student. We can also store and access these data for many students using array of structures. You can check “C – Array of Structures” to know how to store and access these data for many students.

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000

Example program – Another way of declaring C structure:

In this program, structure variable “record” is declared while declaring structure itself. In above structure example program, structure variable “struct student record” is declared inside main function which is after declaring structure.

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000

C structure declaration in separate header file:

In above structure programs, C structure is declared in main source file. Instead of declaring C structure in main source file, we can have this structure declaration in another file called “header file” and we can include that header file in main source file as shown below.

Header file name – structure.h

Before compiling and executing below C program, create a file named “structure.h” and declare the below structure.

struct student
{
int id;
char name[20];
float percentage;
} record;

Main file name – structure.c:

In this program, above created header file is included in “structure.c” source file as #include “Structure.h”. So, the structure declared in “structure.h” file can be used in “structure.c” source file.

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000

Uses of structures in C:

  1. C Structures can be used to store huge data. Structures act as a database.
  2. C Structures can be used to send data to the printer.
  3. C Structures can interact with keyboard and mouse to store the data.
  4. C Structures can be used in drawing and floppy formatting.
  5. C Structures can be used to clear output screen contents.
  6. C Structures can be used to check computer’s memory size etc.

Continue on C – Array of Structures….

Continue on C – Passing structure to function….

Continue on C – Structure using Pointer….

Continue on C – Structure within Structure….

Continue on C – Structure Memory Allocation….

Continue on C – Structure Padding….

PrevNext

Share this website !!!



1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

#include <stdio.h>

#include <string.h>

 

structstudent

{

           intid;

           charname[20];

           floatpercentage;

};

 

intmain()

{

           structstudent record={0};//Initializing to null

 

           record.id=1;

           strcpy(record.name,"Raju");

           record.percentage=86.5;

 

           printf(" Id is: %d \n",record.id);

           printf(" Name is: %s \n",record.name);

           printf(" Percentage is: %f \n",record.percentage);

           return0;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

#include <stdio.h>

#include <string.h>

 

structstudent

{

            intid;

            charname[20];

            floatpercentage;

}record;

 

intmain()

{

 

            record.id=1;

            strcpy(record.name,"Raju");

            record.percentage=86.5;

 

            printf(" Id is: %d \n",record.id);

            printf(" Name is: %s \n",record.name);

            printf(" Percentage is: %f \n",record.percentage);

            return0;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

// File name - structure.c

#include <stdio.h>

#include <string.h>

#include "structure.h"   /* header file where C structure is

                            declared*/

 

intmain()

{

 

   record.id=1;

   strcpy(record.name,"Raju");

   record.percentage=86.5;

 

   printf(" Id is: %d \n",record.id);

   printf(" Name is: %s \n",record.name);

   printf(" Percentage is: %f \n",record.percentage);

   return0;

}

Structure is a group of variables of different data types represented by a single name. Lets take an example to understand the need of a structure in C programming.

Lets say we need to store the data of students like student name, age, address, id etc. One way of doing this would be creating a different variable for each attribute, however when you need to store the data of multiple students then in that case, you would need to create these several variables again for each student. This is such a big headache to store data in this way.

We can solve this problem easily by using structure. We can create a structure that has members for name, id, address and age and then we can create the variables of this structure for each student. This may sound confusing, do not worry we will understand this with the help of example.

How to create a structure in C Programming

We use struct keyword to create a structure in C. The struct keyword is a short form of structured data type.

struct struct_name { DataType member1_name; DataType member2_name; DataType member3_name; … };

Here struct_name can be anything of your choice. Members data type can be same or different. Once we have declared the structure we can use the struct name as a data type like int, float etc.

First we will see the syntax of creating struct variable, accessing struct members etc and then we will see a complete example.

How to declare variable of a structure?

struct  struct_name  var_name;

or

struct struct_name { DataType member1_name; DataType member2_name; DataType member3_name; … } var_name;

How to access data members of a structure using a struct variable?

var_name.member1_name; var_name.member2_name; …

How to assign values to structure members?

There are three ways to do this.
1) Using Dot(.) operator

var_name.memeber_name = value;

2) All members assigned in one statement

struct struct_name var_name = {value for memeber1, value for memeber2 …so on for all the members}

3) Designated initializers – We will discuss this later at the end of this post.

Example of Structure in C

#include <stdio.h> /* Created a structure here. The name of the structure is * StudentData. */ struct StudentData{ char *stu_name; int stu_id; int stu_age; }; int main() { /* student is the variable of structure StudentData*/ struct StudentData student; /*Assigning the values of each struct member here*/ student.stu_name = "Steve"; student.stu_id = 1234; student.stu_age = 30; /* Displaying the values of struct members */ printf("Student Name is: %s", student.stu_name); printf("\nStudent Id is: %d", student.stu_id); printf("\nStudent Age is: %d", student.stu_age); return 0; }

Output:

Student Name is: Steve Student Id is: 1234 Student Age is: 30

Nested Structure in C: Struct inside another struct

You can use a structure inside another structure, which is fairly possible. As I explained above that once you declared a structure, the struct struct_name acts as a new data type so you can include it in another struct just like the data type of other data members. Sounds confusing? Don’t worry. The following example will clear your doubt.

Example of Nested Structure in C Programming

Lets say we have two structure like this:
Structure 1: stu_address

struct stu_address { int street; char *state; char *city; char *country; }

Structure 2: stu_data

struct stu_data { int stu_id; int stu_age; char *stu_name; struct stu_address stuAddress; }

As you can see here that I have nested a structure inside another structure.

Assignment for struct inside struct (Nested struct)

Lets take the example of the two structure that we seen above to understand the logic

struct  stu_data  mydata; mydata.stu_id = 1001; mydata.stu_age = 30; mydata.stuAddress.state = "UP"; //Nested struct assignment ..

How to access nested structure members?

Using chain of “.” operator.
Suppose you want to display the city alone from nested struct –

printf("%s",  mydata.stuAddress.city);

Use of typedef in Structure

typedef makes the code short and improves readability. In the above discussion we have seen that while using structs every time we have to use the lengthy syntax, which makes the code confusing, lengthy, complex and less readable. The simple solution to this issue is use of typedef. It is like an alias of struct.

Code without typedef

struct home_address { int local_street; char *town; char *my_city; char *my_country; }; ... struct home_address var; var.town = "Agra";

Code using tyepdef

typedef struct home_address{ int local_street; char *town; char *my_city; char *my_country; }addr; .. .. addr var1; var.town = "Agra";

Instead of using the struct home_address every time you need to declare struct variable, you can simply use addr, the typedef that we have defined.

Designated initializers to set values of Structure members

We have already learned two ways to set the values of a struct member, there is another way to do the same using designated initializers. This is useful when we are doing assignment of only few members of the structure. In the following example the structure variable s2 has only one member assignment.

#include <stdio.h> struct numbers { int num1, num2; }; int main() { // Assignment using using designated initialization struct numbers s1 = {.num2 = 22, .num1 = 11}; struct numbers s2 = {.num2 = 30}; printf ("num1: %d, num2: %d\n", s1.num1, s1.num2); printf ("num1: %d", s2.num2); return 0; }

Output:

num1: 11, num2: 22 num1: 30