0% found this document useful (0 votes)
18 views

C Structure

The document discusses using structures in C to store data of different types together as a single entity. Structures allow grouping of related data and can be used to store information about complex objects like students. The document provides examples to define a structure, declare structure variables, access members and use structures to store details of multiple students.

Uploaded by

qitenicejal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

C Structure

The document discusses using structures in C to store data of different types together as a single entity. Structures allow grouping of related data and can be used to store information about complex objects like students. The document provides examples to define a structure, declare structure variables, access members and use structures to store details of multiple students.

Uploaded by

qitenicejal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

C Structure

Why use structure?


In C, there are cases where we need to store multiple attributes of an entity. It is not
necessary that an entity has all the information of one type only. It can have different
attributes of different data types. For example, an entity Student may have its name
(string), roll number (int), marks (float). To store such type of information regarding
an entity student, we have the following approaches:

o Construct individual arrays for storing names, roll numbers, and marks.
o Use a special data structure to store the collection of different data types.

Let's look at the first approach in detail.

1. #include<stdio.h>
2. void main ()
3. {
4. char names[2][10],dummy; // 2-dimensioanal character array names is used t
o store the names of the students
5. int roll_numbers[2],i;
6. float marks[2];
7. for (i=0;i<3;i++)
8. {
9.
10. printf("Enter the name, roll number, and marks of the student %d",i+1);
11. scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]);
12. scanf("%c",&dummy); // enter will be stored into dummy character at each i
teration
13. }
14. printf("Printing the Student details ...\n");
15. for (i=0;i<3;i++)
16. {
17. printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]);
18. }
19. }

Output
3M
538
Polymorphism in Java | Dynamic Method Dispatch

Enter the name, roll number, and marks of the student 1Arun 90 91
Enter the name, roll number, and marks of the student 2Varun 91 56
Enter the name, roll number, and marks of the student 3Sham 89 69

Printing the Student details...


Arun 90 91.000000
Varun 91 56.000000
Sham 89 69.000000

The above program may fulfill our requirement of storing the information of an
entity student. However, the program is very complex, and the complexity increase
with the amount of the input. The elements of each of the array are stored
contiguously, but all the arrays may not be stored contiguously in the memory. C
provides you with an additional and simpler approach where you can use a special
data structure, i.e., structure, in which, you can group all the information of different
data type regarding an entity.

What is Structure
Structure in c is a user-defined data type that enables us to store the collection of
different data types. Each element of a structure is called a member. Structures ca;
simulate the use of classes and templates as it can store various information

The ,struct keyword is used to define the structure. Let's see the syntax to define the
structure in c.

1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };

Let's see the example to define a structure for an entity employee in c.

1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };

The following image shows the memory allocation of the structure employee that is
defined in the above example.

Here, struct is the keyword; employee is the name of the structure; id, name,
and salary are the members or fields of the structure. Let's understand it by the
diagram given below:

Declaring structure variable


We can declare a variable for the structure so that we can access the member of the
structure easily. There are two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.

1st way:

Let's see the example to declare the structure variable by struct keyword. It should be
declared within the main function.

1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };

Now write given code inside the main() function.

1. struct employee e1, e2;

The variables e1 and e2 can be used to access the values stored in the structure.
Here, e1 and e2 can be treated in the same way as the objects in C++ and Java.

2nd way:

Let's see another way to declare variable at the time of defining the structure.

1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. }e1,e2;

Which approach is good


If number of variables are not fixed, use the 1st approach. It provides you the
flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable
in main() function.

Accessing members of the structure


There are two ways to access structure members:

1. By . (member or dot operator)


2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by. (member) operator.

1. p1.id

C Structure example
Let's see a simple example of structure in C language.

1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }

Output:

employee 1 id : 101
employee 1 name : Sonoo Jaiswal

Let's see another example of the structure in C language to store many employees
information.

1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. int main( )
9. {
10. //store first employee information
11. e1.id=101;
12. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
13. e1.salary=56000;
14.
15. //store second employee information
16. e2.id=102;
17. strcpy(e2.name, "James Bond");
18. e2.salary=126000;
19.
20. //printing first employee information
21. printf( "employee 1 id : %d\n", e1.id);
22. printf( "employee 1 name : %s\n", e1.name);
23. printf( "employee 1 salary : %f\n", e1.salary);
24.
25. //printing second employee information
26. printf( "employee 2 id : %d\n", e2.id);
27. printf( "employee 2 name : %s\n", e2.name);
28. printf( "employee 2 salary : %f\n", e2.salary);
29. return 0;
30. }

Output:

employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000
Program Store Information of Students Using Structure

Write a C program to store the information of Students using Structure. The


information of each student to be stored is:
Each Student Record should have:
Name
Roll Number
Age
Total Marks

The ‘struct’ keyword is used to create the student structure as:


struct Student
{
char* name;
int roll_number;
int age;
double total_marks;
};
 Get the number of Students whose details are to be stored. Here we are
taking 5 students for simplicity.
 Create a variable of Student structure to access the records. Here it is
taken as a ‘student’
 Get the data of n students and store it in student fields with the help of
the dot (.) operator
Syntax:
student[i].member = value;
After all the data is stored, print the records of each student using the dot (.) operator
and loop.
Syntax:
student[i].member;
Below is the implementation of the above approach:

 C

// C Program to Store Information


// of Students Using Structure
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Create the student structure


struct Student {
char* name;
int roll_number;
int age;
double total_marks;
};

// Driver code
int main()
{
int i = 0, n = 5;

// Create the student's structure variable


// with n Student's records
struct Student student[n];

// Get the students data


student[0].roll_number = 1;
student[0].name = "Geeks1";
student[0].age = 12;
student[0].total_marks = 78.50;

student[1].roll_number = 5;
student[1].name = "Geeks5";
student[1].age = 10;
student[1].total_marks = 56.84;

student[2].roll_number = 2;
student[2].name = "Geeks2";
student[2].age = 11;
student[2].total_marks = 87.94;

student[3].roll_number = 4;
student[3].name = "Geeks4";
student[3].age = 12;
student[3].total_marks = 89.78;

student[4].roll_number = 3;
student[4].name = "Geeks3";
student[4].age = 13;
student[4].total_marks = 78.55;
// Print the Students information
printf("Student Records:\n\n");
for (i = 0; i < n; i++)
{
printf("\tName = %s\n", student[i].name);
printf("\tRoll Number = %d\n", student[i].roll_number);
printf("\tAge = %d\n", student[i].age);
printf("\tTotal Marks = %0.2f\n\n", student[i].total_marks);
}

return 0;
}

Output:
Student Records:

Name = Geeks1
Roll Number = 1
Age = 12
Total Marks = 78.50

Name = Geeks5
Roll Number = 5
Age = 10
Total Marks = 56.84

Name = Geeks2
Roll Number = 2
Age = 11
Total Marks = 87.94

Name = Geeks4
Roll Number = 4
Age = 12
Total Marks = 89.78

Name = Geeks3
Roll Number = 3
Age = 13
Total Marks = 78.55

Example:

Code:
#include <stdio.h>
struct Rectangle
{
int a, b, c, d;
};

int main()
{
// Examples using designated initialization
struct Rectangle R1 = {.b = 0, .c = 1, .a = 2};
struct Rectangle R2 = {.a = 20, .c = 23, .b = 21, .d = 15};

printf ("a = %d, b = %d, c = %d, d = %d\n", R1.a, R1.b, R1.c, R1.d);
printf ("a = %d, b = %d, c = %d, d = %d\n", R2.a, R2.b, R2.c, R2.d);
return 0;
}
Copy
Output:
a = 2, b = 0, c = 1, d = 0
a = 20, b = 21, c = 23, d = 15
Example- 2: Assign and access structure members

Code:
#include <stdio.h>
#include <string.h>
struct Student
{
char f_name[20]; // first name
char l_name[20]; // last name
int id_number; // social security number
double grade_point; // grade point average
};

int main() {
// Assign values to members of S1
struct Student S1 = {"Rosa", "Rowe", 123, 88.89};

// Assign values to members of S2


struct Student S2 = {"Kyla", "Chavez", 124, 91.56};

// Print the values the members S1


printf("Student details:\n");
printf("\nFirst name: %s", S1.f_name);
printf("\nLast name: %s", S1.l_name);
printf("\nSocial security number: %d", S1.id_number);
printf("\nGrade point average: %5.2f", S1.grade_point);

// Print the values the members S2


printf("\n\nFirst name: %s", S2.f_name);
printf("\nLast name: %s", S2.l_name);
printf("\nSocial security number: %d", S2.id_number);
printf("\nGrade point average: %5.2f", S2.grade_point);
return 0;
}
Copy
Output:
Student details:
First name: Rosa
Last name: Rowe
Social security number: 123
Grade point average: 88.89

First name: Kyla


Last name: Chavez
Social security number: 124
Grade point average: 91.56
Copy Structures

A structure can also be assigned to another. Here is an example where the values of S1
are copied to S2:

Code:
#include <stdio.h>
#include <string.h>
struct Student
{
char f_name[20]; // first name
char l_name[20]; // last name
int id_number; // social security number
double grade_point; // grade point average
};

int main() {

// Assign values to members of S1


struct Student S1 = {"Rosa", "Rowe", 123, 88.89};

// the values of S1 are copied to S2:


struct Student S2;
S2 = S1;

// Print the values the members S1


printf("Student details:\n");
printf("\nFirst name: %s", S1.f_name);
printf("\nLast name: %s", S1.l_name);
printf("\nSocial security number: %d", S1.id_number);
printf("\nGrade point average: %5.2f", S1.grade_point);

// Print the values the members S2


printf("\n\nFirst name: %s", S2.f_name);
printf("\nLast name: %s", S2.l_name);
printf("\nSocial security number: %d", S2.id_number);
printf("\nGrade point average: %5.2f", S2.grade_point);
return 0;
}

Structures as Function Arguments


So far, we have learned the declaration, initialization, and printing of the
data members of structures. Now, you must wonder how we can pass an
entire structure or its members to a function. So, yes, we can do that. While
passing structure as a function argument, structure variables are treated the
same as variables of primitive data types. The basic syntax for passing
structure as a function argument is
Syntax:
// passing by value
returnTypeOfFunction functionName (struct sturcture_name variable_name);
functionName(vaiable_name);
// passing by reference
returnTypeOfFunction functionName (struct structure_name* varible_name);
functionName(&variable_name);

Let's see an example for more understanding:

Example

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

struct Student
{
char name[50];
char section;
int class;
};

// pass by value
void printStudent(struct Student var) {

printf("Student name : %s\n", var.name);


printf("Student section : %c\n", var.section);
printf("Student class : %d\n", var.class);
}

// pass by reference
void changeStudent(struct Student* var)
{

var->class = 6;
var->section = 'B';
}

int main(){
struct Student student1 = {"student_name", 'A', 5}; // initialising the object

// passing by value
printStudent(student1);

// passing by reference
changeStudent(&student1);

return 0;
}

Output:

Student name : student_name


Student section : A
Student class : 5
In the above code, we have created a structure Student and declared some
members for it to store the data of students in it. After that, we created an
instance and initialized all of the structure members. There were two
functions: in function printStudent(), we passed the structure by using the
pass-by-value concept, while in function changeStudent(), we passed the
structure by pass-by-reference.
While we are passing values by reference we get a structure pointer in the
function

Limitations of Structures
 The C structure does not allow the struct data type to be treated like built-in
data types.
 We cannot use operators like +,- etc. on Structure variables.
 No Data Hiding: C Structures do not permit data hiding. Structure members
can be accessed by any function, anywhere in the scope of the Structure.
 Functions inside Structure: C structures do not permit functions inside the
Structure
 Static Members: C Structures cannot have static members inside their body
 Access Modifiers: C Programming language does not support access
modifiers. So they cannot be used in C Structures.
 Construction creation in Structure: Structures in C cannot have a constructor
inside Structures.
Conclusion
 Structure in C is a user-defined data type. It binds the two or more data
types or data structures together.
 The Structure is created using struct keyword and its variables are
created using struct keyword and structure name.
 A data type created using structure in C can be treated as other
primitive data types of C to declare a pointer for it, pass it as a function
argument, or return from the function.
 There are three ways to initialize the structure variables: using the dot
operator, using curly braces, or designated initialization.
 One structure can consist of another structure, or more means there
can be nested Structures.
 With the help of typedef, we can give short or new names to a structure
data type.

You might also like