0% found this document useful (0 votes)
3 views11 pages

C Structures

C structures are user-defined data types that group different data types into a single type using the 'struct' keyword. They are used to create complex data types, represent real-world entities, and support operations like accessing members, initializing, and nesting structures. Arrays of structures allow for efficient management of multiple instances of related data, making it easier to handle large datasets.

Uploaded by

aboliwable96k
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

C Structures

C structures are user-defined data types that group different data types into a single type using the 'struct' keyword. They are used to create complex data types, represent real-world entities, and support operations like accessing members, initializing, and nesting structures. Arrays of structures allow for efficient management of multiple instances of related data, making it easier to handle large datasets.

Uploaded by

aboliwable96k
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

C Structures

In C, a structure is a user-defined data type that can be used to group items of possibly
different types into a single type.
 The struct keyword is used to define a structure. The items in the structure are called its
members and they can be of any valid data type.
 Applications of structures involve creating data structures Linked List and Tree.
Structures are also used to represent real world objects in a software like Students and
Faculty in a college management software.
#include <stdio.h>

// Defining a structure

struct A {

int x;

};

int main() {

// Creating a structure variable

struct A a;

// Initializing member

a.x = 11;

printf("%d", a.x);

return 0;

Output
11
Explanation: In this example, a structure A is defined to hold an integer member x. A
variable a of type struct A is created and its member x is initialized to 11 by accessing it
using dot operator. The value of a.x is then printed to the console.
Basic Operations of Structure
Following are the basic operations commonly used on structures:

1. Access Structure Members

 To access or modify members of a structure, we use the ( . ) dot operator. This is


applicable when we are using structure variables directly.
 In the case where we have a pointer to the structure, we can also use the arrow operator to
access the members.

2. Initialize Structure Members

 Structure members cannot be initialized with the declaration. For example, the following
C program fails in the compilation.
#include <stdio.h>

// Defining a structure to represent a student


struct Student
{
char name[50];
int age;
float grade;
};
int main()
{

// Declaring and initializing a structure variable


struct Student s1 = {"Rahul", 20, 18.5};

// Designated Initializing another structure


struct Student s2 = {.age = 18, .name = "Vikas", .grade =
22};

// Accessing structure members


printf("%s\t%d\t%.2f\n", [Link], [Link], [Link]);
printf("%s\t%d\t%.2f\n", [Link], [Link], [Link]);

return 0;
}

Output
Rahul 20 18.50
Vikas 18 22.00
We can initialize structure members in 4 ways which are as follows:
Default Initialization
 By default, structure members are not automatically initialized to 0 or NULL.
 Uninitialized structure members will contain garbage values. However, when a structure
variable is declared with an initializer, all members not explicitly initialized are zero-
initialized.
Note: We cannot initialize the arrays or strings using assignment operator after variable
declaration.
Initialization using Initializer List
struct structure_name str = {value1, value2, value3 ....};
In this type of initialization, the values are assigned in sequential order as they are declared in
the structure template.

typedef for Structures

 The typedef keyword is used to define an alias for the already existing datatype. In
structures, we have to use the struct keyword along with the structure name to define the
variables.
 Sometimes, this increases the length and complexity of the code. We can use the typedef
to define some new shorter name for the structure.
#include <stdio.h>
// Defining structure
typedef struct {
int a;
} str1;
// Another way of using typedef with structures
typedef struct {
int x;
} str2;

int main() {

// Creating structure variables using new names


str1 var1 = { 20 };
str2 var2 = { 314 };

printf("var1.a = %d\n", var1.a);


printf("var2.x = %d\n", var2.x);
return 0;
}

Output

var1.a = 20
var2.x = 314
Explanation: In this code, str1 and str2 are defined as aliases for the unnamed structures,
allowing the creation of structure variables (var1 and var2) using these new names. This
simplifies the syntax when declaring variables of the structure.
Size of Structures
 The size of a structure is not always equal to the sum of its members’ sizes because of
structure padding.
 Structure padding means adding extra empty bytes in memory to align data properly.
 Padding helps the CPU access data faster by reducing read cycles.
 Sometimes, we need to remove these extra bytes to save memory — this is called
structure packing.
 Structure packing forces the compiler to store members without gaps.
It can be done using:
1. #pragma pack(1)
2. __attribute((packed))__
To know more about structure padding and packing, refer to this article - Structure Member
Alignment, Padding and Data Packing.
Nested Structures
In C, a nested structure refers to a structure that contains another structure as one of its
members. This allows you to create more complex data types by grouping multiple structures
together, which is useful when dealing with related data that needs to be grouped within a
larger structure.
There are two ways in which we can nest one structure into another:
 Embedded Structure Nesting: The structure being nested is also declared inside the
parent structure.
 Separate Structure Nesting: Two structures are declared separately and then the
member structure is nested inside the parent structure.
Accessing Nested Members

 We can access nested Members by using the same ( . ) dot operator two times.
#include <stdio.h>
// Child structure declaration
struct child {
int x;
char c;
};
// Parent structure declaration
struct parent {
int a;
struct child b;
};
int main() {
struct parent p = { 25, 195, 'A' };
// Accessing and printing nested members
printf("p.a = %d\n", p.a);
printf("p.b.x = %d\n", p.b.x);
printf("p.b.c = %c", p.b.c);
return 0;
}
Output

p.a = 25
p.b.x = 195
p.b.c = A
Explanation: In this code, the structure parent contains another structure child as a member.
The parent structure is then initialized with values, including the values for the child
structure's members.
Uses of Structure in C
 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.
 It can also be used in data organization where a large amount of data can be stored in
different fields.
 Structures are used to create data structures such as trees, linked lists, etc.
 They can also be used for returning multiple values from a function.
Array of Structures in C



An array of structures is simply an array where each element is a
structure. It allows you to store several structures of the same type in a
single array.
#include <stdio.h>
#include <string.h>

// Structure definition
struct A {
int var;
};

int main() {

// Declare an array of structures


struct A arr[2];

arr[0].var = 10;
arr[1].var = 20;

for (int i = 0; i < 2; i++)


printf("%d\n", arr[i].var);

return 0;
}

Output
10
20
Explanation: We define a Person structure with name and age as members. An array of 2
Person structures is declared, and each element is populated with different people’s details.
A for loop is used to iterate through the array and print each person's information.
Array of Structure Declaration
Once you have already defined structure, the array of structure can be defined in a similar
way as any other variable.
struct struct_name arr_name [size];
Need for Array of Structures
Suppose we have 50 employees, and we need to store the data of 50 employees. So for that,
we need to define 50 variables of struct Employee type and store the data within that.
However, declaring and handling the 50 variables is not an easy task. Let's imagine a bigger
scenario, like 1000 employees.
So, if we declare the variable this way, it's not possible to handle this.
struct Employee emp1, emp2, emp3, .. . ... . .. ... emp1000;
For that, we can define an array whose data type will be struct Employee soo that will be
easily manageable.
 Arrays of structures allow you to group related data together and handle multiple
instances of that data more efficiently.
 It is particularly useful when you want to manage large datasets (such as a list of
employees, students, or products) where each element has a consistent structure.
Basic Operations on Array of Structures
Following are the basic operations on array of structures:

Initialization

 A structure can be initialized using initializer list and so can be the array. Therefore, we
can initialize the array of structures using nested initializer list:
 We can also skip the nested braces, but it is not recommended as we can easily lose the
count of the element/member and may mess up the initialization.
 GNU C compilers support designated initialization for structures. So we can also use
this in the initialization of an array of structures:

// Structure definition
struct A {
int var;
char c;
};

int main() {

// Declaration and initialization using nested


// initializer list
struct A arr1[2] = { {1, 'a'}, {2, 'b'} };

// Declaration and initialization using non-nested


// initializer list
struct A arr2[2] = { 10, 'A', 20, 'B' };

// Designated initialization
struct A arr3[2] = { {.c = 'A', .var = 10},
{.var = 2, .c = 'b'} };

Output

1a
2b
10 A
20 B

10 A
2b

Access and Update Members

To access the members of a structure in an array, use the index of the array element
followed by the dot (.) operator. The general syntax is:
arr_name[index].member_name
where,
 arr_name: The name of the array of structures.
 index: The index of the structure element in the array.
 member_name: The member within the structure you want to access.

printf("%c
",arr[1].c);

// Update the value and access again


arr[1].c = 'Z';
printf("%c",arr[1].c);

Output

b
Z

Traversal

The array of structure can be easily traversed in the same way we traverse the array.
#include <stdio.h>
#include <string.h>

// Structure definition
struct A {
int var;
char c;
};

int main() {
struct A arr[5] = { {1, 'a'}, {2, 'b'}, {3, 'c'},
{4, 'd'}, {5, 'e'} };

// Traverse arr
for (int i = 0; i < 5; i++)
printf("%d %c\n", arr[i].var, arr[i].c);

return 0;
}

Output

1a
2b
3c
4d
5e

Example of Array of Structure


The below code demonstrates the application of array of structure inside a C program:

Store Student Information

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

// Structure definition
struct Student {
char name[50];
int age;
float marks;
};

int main() {

// Declaration and initialization of an array of structures


struct Student students[3] = {
{"Nikhil", 20, 85.5},
{"Shubham", 22, 90.0},
{"Vivek", 25, 78.0}
};
// Traversing through the array of structures and displaying the data
for (int i = 0; i < 3; i++) {
printf("Student %d:\n", i+1);
printf("Name: %s\n", students[i].name);
printf("Age: %d\n", students[i].age);
printf("Marks: %.2f\n\n", students[i].marks);
}
return 0;
}
Output

Student 1:
Name: Nikhil
Age: 20
Marks: 85.50

Student 2:
Name: Shubham
Age: 22
Marks: 90.00

Student 3:
Name: Vivek
Age: 25
Marks: 78.00

Find the Size of Array of Structures

The array of structures are also affected by the concept called structure padding.
#include <stdio.h>
#include <string.h>
struct Student {
char name[50];
int age;
float marks;
};

int main() {
struct Student students[3] = {
{"John", 20, 85.5},
{"Alice", 22, 90.0},
{"Bob", 25, 78.0}
};
// Printing size of students
printf("%ld", sizeof(students));

return 0;
}
Output

180

You might also like