0% found this document useful (0 votes)
2 views99 pages

Structure in C

The document explains the concept of structures in C programming, which are user-defined data types that group related variables of different data types into a single type. It details how to define structures, create structure variables, access structure members, and initialize them, emphasizing the advantages of using structures over individual arrays for managing related data. The document also provides syntax examples and methods for accessing and manipulating structure members using both structure variables and pointers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views99 pages

Structure in C

The document explains the concept of structures in C programming, which are user-defined data types that group related variables of different data types into a single type. It details how to define structures, create structure variables, access structure members, and initialize them, emphasizing the advantages of using structures over individual arrays for managing related data. The document also provides syntax examples and methods for accessing and manipulating structure members using both structure variables and pointers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 99

STRUCTURE IN C

BY SANNIDDHA CHAKRABARTI
WHY WE NEED IT?

We are often required to work with values of different data types having certain relationships among them. For
example, a book is described by its title (string), author (string), price (double), number of pages (integer), etc.
 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:

1. Construct individual arrays for storing names, roll numbers, and marks.
2. Use a special data structure to store the collection of different data types. Instead of using three different
variables, these values can be stored in a single struct variable.
WHY WE NEED IT? (CONTD.)

1. Construct individual arrays for storing names, roll numbers, and marks.
WHY WE NEED IT? (CONTD.)

2. Use a special data structure.


DEFINITION

 The structure in C is a derived or user-defined data type that can be used to group several related variables of
different pre-defined data-types into a single type.

 It is somewhat similar to an Array. The only difference is that array is used to store collection of similar data types
for example, an integer values, whereas structure can store collection of any type of data (int, float, char, etc).

 It reduces the complexity of the program.


Define Structures
DEFINE STRUCTURES : SYNTAX

We have to define (or create or declare) structure in C before using it in our program. In structure declaration, we
declare each of its members variables along with their datatype.
The struct keyword is used to define the structure in the C programming language. The items in the structure are
called its member or field and they can be of any valid data type.
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure prototype and no memory is allocated to the structure
in the declaration.
DEFINE STRUCTURES : EXAMPLE
Create Structure Variables
CREATE STRUCT VARIABLES

When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and
to access and manipulate the members of the structure, you need to declare its variable first.
Like when we declare a variable of data type integer, a certain amount of memory (4 bytes for int) is allocated to the
variable.
Similarly, when we declare variables of given structure type, a certain amount of memory is allocated to the structure
variables.
There are two ways to declare structure variable:
1. By struct keyword within main() function.
2. By declaring variables at the time of defining the structure.
CREATE STRUCT VARIABLES (CONTD.)

Create Structure
Variables

By declaring variables
By struct keyword
at the time of defining
within main() function
the structure
CREATE STRUCT VARIABLES (1ST WAY)

1. By struct keyword within main() function

To declare a structure variable inside main() function, write the structure name along with the "struct" keyword
followed by the name of the structure variable. This structure variable will be used to access and manipulate the
structure members.

Syntax:
struct structure_name variable1, variable2, .......;
CREATE STRUCT VARIABLES (1ST WAY) (CONTD.)

1. By struct keyword within main() function

Example:
struct student student1, student2;
Here we declare two variables of structure type student. In other words, student1 and student2 are struct
student variables
This is somewhat similar to declare variables of primitive data-type (int, float, double, etc.). For example,
int age, id;
Here age and roll_no are int variables i.e., integer variables.
CREATE STRUCT VARIABLES (2ND WAY)

2. By declaring variables at the time of defining the structure.

Syntax:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
CREATE STRUCT VARIABLES (2ND WAY) (CONTD.)

2. By declaring variables at the time of defining the structure.

Example:
struct student
{
int id;
char name[10];
float marks;
}student1, student2;
CREATE STRUCT VARIABLES (CONTD.)
Access Structure Members
ACCESS STRUCTURE MEMBERS

To store a value in a variable, we have to access the variable. In case of primitive data type, variables are accessed by
their names.
To store values in structure variables, we have to access the structure members. For example, to store the information
of student1, we have to access its members i.e., roll_no, name, marks.
There are two ways for accessing members of a structure.
1. Using structure variable.
2. Using Structure pointer.
ACCESS STRUCTURE MEMBERS (CONTD.)

Access Structure
Members

Using structure Using structure


variable pointer

Using ( * ) asterisk or indirection


operator and dot ( . ) operator.

Using arrow ( -> ) operator or


membership operator or struct dereference
operator
ACCESS STRUCTURE MEMBERS (CONTD.)

1. Using structure variable

The member or dot (.) operator is used to access the struct members via the struct variable.

Syntax:
variable_name.member1;
variable_name.member2;
ACCESS STRUCTURE MEMBERS (CONTD.)

1. Using structure variable

Example:
Suppose, you want to access the id of student2. Let's see the code to access the id member of student2
variable by . (member) operator.
student2.id;
ACCESS STRUCTURE MEMBERS (CONTD.)

1. Using structure variable

100 100 101 101


0 4 4 8

student1

int id char name[10] float marks

student1.id;
student1.name;
student1.marks;
ACCESS STRUCTURE MEMBERS (CONTD.)

1. Using structure variable

200 200 201 201


0 4 4 8

student2

int id char name[10] float marks

student2.id;
student2.name;
student2.marks;
ACCESS STRUCTURE MEMBERS (CONTD.)

2. Using Structure pointer

We can define a pointer that points to the structure like any other variable. Such pointers are generally called
Structure Pointers.
Complex data structures like Linked lists, trees, graphs, etc. are created with the help of structure pointers.
There are two ways to access the member of the structure using Structure pointer:
 Using ( * ) asterisk or indirection operator and dot ( . ) operator.
 Using arrow ( -> ) operator or membership operator or struct dereference operator.
ACCESS STRUCTURE MEMBERS (CONTD.)

Structure pointer
We define pointer to any predefined datatype (eg: int, float, double, char, etc.), using the syntax:
datatype *ptr_name;
For example,
int *ptr;

Structure is a custom or user-defined datatype. In the above example, data-type defined by the user or structure type is
struct student. So, to define a structure pointer of this type, we write struct student in place of datatype.
ACCESS STRUCTURE MEMBERS (CONTD.)

Structure pointer
The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. A structure pointer points
to a structure i.e., holds the address of a structure.

Syntax:
struct structure_name *ptr_name;

Example,
struct student *ptr;
ACCESS STRUCTURE MEMBERS (CONTD.)

Using ( * ) asterisk or indirection operator and dot ( . ) operator :

Syntax:
Step 1: Declare a pointer to the structure
// Declare two pointers to structure
struct structure_name *ptr1 // Pointer to access struct variable1
struct structure_name *ptr2 // Pointer to access struct variable2

Step 2: Assign the address of the struct variables to pointer


ptr1 = &variable1;
ptr2 = &variable2;
ACCESS STRUCTURE MEMBERS (CONTD.)

Step 3: Access the structure members with pointer

(*ptr1).member_name1;
(*ptr1).member_name2;
(*ptr2).member_name1;
(*ptr2).member_name2;
ACCESS STRUCTURE MEMBERS (CONTD.)

Using ( * ) asterisk or indirection operator and dot ( . ) operator :

Example:
Step 1: Declare a pointer to the structure
// Declare two pointers to structure
// Pointer to student1 variable
struct student *ptr1;
// Pointer to student2 variable
struct student *ptr2;
ACCESS STRUCTURE MEMBERS (CONTD.)

Step 2: Assign the address of the struct variables to pointers

//Assign the address of student1 variable


ptr1 = &student1;
//Assign the address of student2 variable
ptr2 = &student1;
ACCESS STRUCTURE MEMBERS (CONTD.)

Step 3: Access the structure members with pointer

(*ptr1).id;
(*ptr1).name;
(*ptr1).marks;
(*ptr2).id;
(*ptr2).name;
(*ptr2).marks;
(*ptr1).name returns the name of student1, just like student1.name does.
ACCESS STRUCTURE MEMBERS (CONTD.)

Using ( * ) asterisk or indirection operator and dot ( . ) operator :

100 100 101 101


0 4 4 8

student1

int id char name[10] float marks

(*ptr1).id;
1000 (*ptr1).name;
ptr1 (*ptr1).marks;
ACCESS STRUCTURE MEMBERS (CONTD.)

Using ( * ) asterisk or indirection operator and dot ( . ) operator :

200 200 201 201


0 4 4 8

student2

int id char name[10] float marks

(*ptr2).id;
2000 (*ptr2).name;
ptr2 (*ptr2).marks;
ACCESS STRUCTURE MEMBERS (CONTD.)

Using arrow ( -> ) operator or membership operator:

Syntax:
Step 1: Declare a pointer to the structure
// Declare two pointers to structure
struct structure_name *ptr1 // Pointer to access struct variable1
struct structure_name *ptr2 // Pointer to access struct variable2

Step 2: Assign the address of the struct variables to pointer


ptr1 = &variable1;
ptr2 = &variable2;
ACCESS STRUCTURE MEMBERS (CONTD.)

Step 3: Access the structure members with pointer

ptr1 -> member_name1;


ptr1 -> member_name2;
ptr2 -> member_name1;
ptr2 -> member_name2;
ACCESS STRUCTURE MEMBERS (CONTD.)

Using arrow ( -> ) operator or membership operator:

Example:
Step 1: Declare a pointer to the structure
// Declare two pointers to structure
// Pointer to student1 variable
struct student *ptr1;
// Pointer to student2 variable
struct student *ptr2 ;
ACCESS STRUCTURE MEMBERS (CONTD.)

Step 2: Assign the address of the struct variables to pointers

//Assign the address of student1 variable


ptr1 = &student1;
//Assign the address of student2 variable
ptr2 = &student1;
ACCESS STRUCTURE MEMBERS (CONTD.)

Step 3: Access the structure members with pointer

ptr1 -> id;


ptr1 -> name;
ptr1 -> marks;
ptr2 -> id;
ptr2 -> name;
ptr2 -> marks;
ptr1→name returns the name of student1, just like student1.name does.
ptr1→name returns the name of student1, just like (*ptr1).name does.
ACCESS STRUCTURE MEMBERS (CONTD.)

Using arrow ( -> ) operator or membership operator:

100 100 101 101


0 4 4 8

student1

int id char name[10] float marks

ptr1 -> id;


1000 ptr1 -> name;
ptr1 ptr1 -> marks;
ACCESS STRUCTURE MEMBERS (CONTD.)

Using arrow ( -> ) operator or membership operator:

200 200 201 201


0 4 4 8

student2

int id char name[10] float marks

ptr2 -> id;


2000 ptr2 -> name;
ptr2 ptr2 -> marks;
Structure Initialization
STRUCTURE INITIALIZATION

Structure members cannot be initialized with the declaration. For example, the following C program fails in the
compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for the above error is simple. When a datatype is declared, no memory is allocated for it. Memory is
allocated only when variables are created.
STRUCTURE INITIALIZATION (CONTD.)

By default, structure members are not automatically initialized to 0 or NULL. Uninitialized structure members will
contain garbage values.
STRUCTURE INITIALIZATION (CONTD.)

We can initialize structure members in 3 ways which are as follows:


1. Using Assignment Operator.
2. Using Initializer List.
3. Using Designated Initializer List.
STRUCTURE INITIALIZATION (CONTD.)

Structure Initialization

Using Assignment Using Designated


Using Initializer List
Operator Initializer List

Using . (dot) operator

Using * (asterisk) and . (dot) operator

Using -> (structure pointer) operator


STRUCTURE INITIALIZATION (CONTD.)

1. Using Assignment Operator

To initialize a structure, i.e., to store data in structure using assignment operator, we have access the structure
members. Remember that, we can access the structure members using 3 ways.
Syntax (Using . (dot) operator) – It uses structure variables:
variable_name.member1 = value1;
variable_name.member2 = value2;

Syntax (Using * (asterisk) and . (dot) operator) – It uses structure pointers:


(*pointer_name).member1 = value1;
(*pointer_name).member2 = value2;
STRUCTURE INITIALIZATION (CONTD.)

Syntax (Using -> (structure pointer) operator) – It uses structure pointers:

pointer_name -> member1 = value1;


pointer_name -> member2 = value2;
STRUCTURE INITIALIZATION (CONTD.)

1. Using Assignment Operator

Example (Using . (dot) operator) – It uses structure variables:


student1.id = 12;
student2.marks = 89.03;

Example (Using * (asterisk) and . (dot) operator) – It uses structure pointers:


(*ptr1).id = 12;
(*ptr2).marks = 89.03;
STRUCTURE INITIALIZATION (CONTD.)

Example (Using -> (structure pointer) operator) – It uses structure pointers:

ptr1 -> id = 12;


ptr2 -> marks = 89.03;
STRUCTURE INITIALIZATION (CONTD.)

Remember that strings in C are actually an array of characters, and unfortunately, you can't assign a value to an array
like this:
student2.name = “Ravi”;
Or
(*ptr2).name = “Ravi”;
Or
ptr2->name = “Ravi”;

An error will occur:


prog.c:12:15: error: assignment to expression with array type
STRUCTURE INITIALIZATION (CONTD.)

However, there is a solution for this! You can use the strcpy() function and assign the value to
student2.name, like this:
strcpy(student2.name, “Ravi”);
Or
strcpy((*ptr2).name, “Ravi”);
Or
strcpy(ptr2->name, “Ravi”);
STRUCTURE INITIALIZATION (CONTD.)

Using Structure Variable:

100 100 101 101


0 4 4 8

student1 12 David 65.00

int id char name[10] float marks

student1.id = 12;
strcpy(student1.name, “David”);
student1.marks = 65.00;
STRUCTURE INITIALIZATION (CONTD.)

Using Structure Variable:

200 200 201 201


0 4 4 8

student2 17 Ravi 89.03

int id char name[10] float marks

student2.id = 17;
strcpy(student1.name, “Ravi”);
student1.marks = 89.03;
STRUCTURE INITIALIZATION (CONTD.)

Using Structure Pointer:

100 100 101 101


0 4 4 8

student1 12 David 65.00

int id char name[10] float marks

(*ptr1).id = 12; ptr1 -> id = 12;


1000
strcpy((*ptr1).name, “David”); strcpy(ptr1 -> name, “David”);
ptr1 (*ptr1).marks = 65; ptr1 -> marks = 65;
STRUCTURE INITIALIZATION (CONTD.)

Using Structure Pointer:

200 200 201 201


0 4 4 8

student2 17 Ravi 89.03

int id char name[10] float marks

(*ptr2).id = 17; ptr2 -> id = 17;


2000
strcpy((*ptr2).name, “Ravi”); strcpy(ptr2 -> name, “Ravi”);
ptr2 (*ptr2).marks = 89.03; ptr2 -> marks = 89.03;
STRUCTURE INITIALIZATION (CONTD.)

2. Using Initializer List

Syntax:
struct structure_name variable_name = {value1, value2, value3, …};

 In this type of initialization, the values are assigned in sequential order as they are declared in the structure
template.
 The order of the inserted values must match the order of the variable types declared in the structure.
STRUCTURE INITIALIZATION (CONTD.)

2. Using Initializer List

Example:
struct student student1 = {12, “David”, 65};
struct student student2 = {17, “Ravi”, 89.03};
STRUCTURE INITIALIZATION (CONTD.)

3. Using Designated Initializer List

Syntax:
struct structure_name variable_name = { .member1 = value1, .member2 =
value2, .member3 = value3 };
STRUCTURE INITIALIZATION (CONTD.)

3. Using Designated Initializer List

Example:
struct student student1 = {.id = 12, .name = “David”, .marks = 65};
struct student student2 = {.id = 17, .name = “Ravi”, .marks = 89.03};
STRUCTURE INITIALIZATION (CONTD.)
VISUALIZE THE STRUCTURE

Define Structures
Create Structure Variables
Access Structure Members
Structure Initialization
EXAMPLE

Define Structures
EXAMPLE (CONTD.)

Create Structure Variables


By struct keyword within main() function By declaring variables at the time of defining the structure.
EXAMPLE (CONTD.)

Structure Initialization
Using Assignment Operator : Using . (dot) operator
EXAMPLE (CONTD.)

Structure Initialization
Using Assignment Operator : Using * (asterisk) and . (dot) operator
EXAMPLE (CONTD.)

Structure Initialization
Using Assignment Operator : Using -> (structure pointer) operator
EXAMPLE (CONTD.)

Structure Initialization
Using Initializer List
EXAMPLE (CONTD.)

Structure Initialization
Using Designated Initializer List
Copy Structures
COPY STRUCTURES

You can also assign one structure to another. The assignment (=) operator can be used to copy a structure directly.

Syntax:
structure_variable1 = structure_variable2;

Example:
student1 = student2;
COPY STRUCTURES (CONTD.)
COPY STRUCTURES (CONTD.)

You can also use the assignment operator (=) to assign the value of the member of one structure to another.

Syntax:
structure_variable1.member1 = structure_variable2.member1;

Example:
student1.id = student2.id;
COPY STRUCTURES (CONTD.)
COPY STRUCTURES (CONTD.)

Use strcpy() function to assign the value to a string variable instead of using the "= operator".

Syntax:
strcpy(structure_variable1.member1, structure_variable2.member1);

Example:
strcpy(student1.name, student2.name);
COPY STRUCTURES (CONTD.)
Self-Referential
Structure
SELF-REFERENTIAL STRUCTURE

A structure where one of the members is an integer pointer, i.e. points to an integer i.e., hold the address
of an integer variable:

https://www.programiz.com/online-compiler/593OQ9npWiPsb
SELF-REFERENTIAL STRUCTURE (CONTD.)

A structure where two of the members are integer pointer, i.e. points to an integer i.e., hold the address of
an integer variable:

https://www.programiz.com/online-compiler/15xw9GmILVaIZ
SELF-REFERENTIAL STRUCTURE (CONTD.)

A structure where one of the members is an structure pointer, i.e. points to a structure i.e., hold the address
of a structure:

https://www.programiz.com/online-compiler/2fkIVGYseybMU
SELF-REFERENTIAL STRUCTURE (CONTD.)

A structure where two of the members are structure pointer, i.e. points to a structure i.e., hold the address
of a structure:

https://www.programiz.com/online-compiler/1tH6fqPViMv1P
SELF-REFERENTIAL STRUCTURE (CONTD.)

Self Referential structures are those structures that have one or more pointers which point to the same
type of structure, as their member.
They are extensively used to build complex and dynamic data structures such as linked lists and trees.
SELF-REFERENTIAL STRUCTURE (CONTD.)

Types of Self Referential Structures:


1. Self Referential Structure with Single Link: These structures can have only one self-pointer as their
member. In other words, these structures that have only one pointer which point to the same type of structure,
as their member
2. Self Referential Structure with Multiple Links: Self referential structures with multiple links can have
more than one self-pointers. In other words, these structures that have more than one pointers which point to
the same type of structure, as their member
SELF-REFERENTIAL STRUCTURE (CONTD.)

1. Self Referential Structure with Single Link:


SELF-REFERENTIAL STRUCTURE (CONTD.)

1. Self Referential Structure with Single Link:


SELF-REFERENTIAL STRUCTURE (CONTD.)

2. Self Referential Structure with Multiple Links:


SELF-REFERENTIAL STRUCTURE (CONTD.)

2. Self Referential Structure with Multiple Links:


Typedef
TYPEDEF

The typedef keyword is used to define an alias for the already existing datatype.

Syntax:
typedef existing_name alias_name;
TYPEDEF (CONTD.)

For example, suppose we want to create variables of type unsigned int, then it becomes a tedious task to declare
multiple variables of this type, it will not be very convenient to use these two keywords every time. Instead, you can
define an alias or a shortcut with the typedef keyword as follows
typedef unsigned int unit;
Now, we can create the variables of type unsigned int by writing the following statement:
unit a, b;
instead of writing:
unsigned int a, b;
TYPEDEF (CONTD.)

It is commonly used with structures to simplify the syntax of declaring variables.


In structures, we have to use the struct keyword along with the structure name to define the variables, for example,
struct student student1.
Sometimes, this increases the length and complexity of the code. We can use the typedef to define some new shorter
name for the structure.
TYPEDEF (CONTD.)

Method 1. For defining the structure and creating a typedef simultaneously use:
typedef struct StructName {
// Member definitions
} TypedefName;

Method 2. For defining the Structure first, then creating a typedef use:
struct StructName {
// Member definitions
};
typedef struct StructName TypedefName;
TYPEDEF (CONTD.)

Example:
Method 1.
typedef struct student
{
int id;
char name[10];
float marks;
}student stud;
TYPEDEF (CONTD.)

Example:
Method 2.
struct student
{
int id;
char name[10];
float marks;
};
typedef student stud;
TYPEDEF (CONTD.)

Now we can create variables of type struct student using


stud s1, s2;
instead of writing,
struct student s1, s2;

We can also create structure pointer of type struct student using


stud *ptr;
instead of writing
struct student *ptr;
RETURN MULTIPLE VALUES FROM A FUNCTION

Unfortunately, C and C++ do not allow this directly. But fortunately, with a little bit of clever programming, we can
easily achieve this. Below are the methods to return multiple values from a function in C:
1. By using pointers.
2. By using structures.
3. By using Arrays.

Example: Consider an example where the task is to find the greater and smaller of two distinct numbers. We could
write multiple functions. The main problem is the trouble of calling more than one functions since we need to return
multiple values and of course, having more number of lines of code to be typed.
RETURN MULTIPLE VALUES FROM A FUNCTION (CONTD.)
USES OF STRUCTURE

C structures are used for the following:


1. The structure can be used to define the custom data types that can be used to create some complex data types such
as dates, time, complex numbers, etc. which are not present in the language.
2. It can also be used in data organization where a large amount of data can be stored in different fields.
3. Structures are used to create data structures such as trees, linked lists, etc.
4. They can also be used for returning multiple values from a function.
LIMITATIONS OF C STRUCTURES

In C language, structures provide a method for packing together data of different types. A Structure is a helpful tool to
handle a group of logically related data items. However, C structures also have some limitations.
 Higher Memory Consumption: It is due to structure padding.
 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 so we cannot provide the
associated functions.
 Static Members: C Structure cannot have static members inside its body.
 Construction creation in Structure: Structures in C cannot have a constructor inside Structures.

You might also like