Structure & Dynamic Memory Allocation in C (1)
Structure & Dynamic Memory Allocation in C (1)
Structure
The structure in C 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 the structure in the C programming
language. The items in the structure are called its member and they can be of any valid data type.
C Structure Declaration
We have to declare structure in C before using it in our program. In structure declaration, we specify
its member variables along with their datatype. We can use the struct keyword to declare the structure
in C using the following syntax:
Syntax
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.
#include <stdio.h>
#include <string.h>
int main() {
Output
C Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating variables
of the structure type. We can define structure variables using two methods:
The C dot (.) operator is used for direct member selection via the name of variables of type
struct and union.
Also known as the direct member access operator, it is a binary operator that helps us to extract the
value of members of the structures and unions.
Syntax of Dot Operator
variable_name.member;
variable_name: An instance of a structure or a union.
member: member associated with the created structure or union.
struct str {
int mem;
};
union un {
int mem1;
char mem2;
};
int main()
{
struct str str_name = {
12}; union un un_name;
return 0;
}
Output
Union Member 1: 9
Structure Member: 12
struct base {
struct child {
int i;
} child;
};
int main()
{
struct base s_name = { 12 };
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members hereint 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.
We can initialize structure members in 3 ways which are as follows:
Using Assignment Operator.
Using Initializer List.
Using Designated Initializer List.
// Driver code
int main()
{
// variable declaration after structure template
// initialization with initializer list and designated
// initializer list
struct str1 var1 = { 1, 'A', 1.00, "GeeksforGeeks" },
var2;
struct str2 var3 = { .ff = 5.00, .ii = 5, .cc = 'a' };
var2 = var1;
return 0;
}
Output
Struct 1:
i = 1, c = A, f = 1.000000, s = GeeksforGeeks
Struct 2:
i = 1, c = A, f = 1.000000, s = GeeksforGeeks
Struct 3
i = 5, c = a, f = 5.000000
// defining structure
struct str1 {
int a;
};
// defining new name for str1
typedef struct str1 str1;
int main()
{
// creating structure variables using new names
str1 var1 = { 20 };
str2 var2 = { 314 };
return 0;
}
Output
var1.a = 20
var2.x = 314
Nested Structures
C language allows us to insert one structure into another as a member. This process is called nesting
and such structures are called nested structures.
#include <stdio.h>
struct complex {
int imag;
float real;
};
struct number {
struct complex comp;
int integer;
} num1;
int main() {
return 0;
}
Output
Imaginary Part: 11
Real Part: 5.25
Integer: 6
There are two ways in which we can nest one structure into another:
struct parent {
int member1;
struct member_str member2 {int
member_str1;
char member_str2;
...
}
...
}
One thing to note here is that the declaration of the structure should always be
present before its definition as a structure member. For example, the declaration
below is invalid as the struct mem is not defined when it is declared inside the parent
structure.
struct parent { struct mem
a;
};
struct mem {
int var;
};
struct child b;
};
// driver code
int main()
{
struct parent var1 = { 25, 195, 'A' };
return 0;
}
Output
var1.a = 25
var1.b.x = 195
var1.b.c = A
Structure Pointer in C
We can define a pointer that points to the structure like any other variable. Such pointers
are generally called Structure Pointers. We can access the members of the structure
pointed by the structure pointer using the ( -> ) arrow operator.
// structure declaration
struct Point {
int x, y;
};
int main()
{
struct Point str = { 1, 2 };
// p2 is a pointer to structure p1
struct Point* ptr = &str;
return 0;
}
Output
12
Self-Referential Structures
The self-referential structures in C are those structures that contain references to the same type
as themselves i.e. they contain a member of the type pointer pointing to the same structure
type.
// structure templatetypedef
struct str {
int mem1;
int mem2;
struct str* next;
}str;
// driver codeint
main()
{
str var1 = { 1, 2, NULL };
// pointer to var1str
*ptr1 = &var1;
return 0;
}
Output
var2.mem1: 10
var2.mem2: 20
Such kinds of structures are used in different data structures such as to define the nodes of linked
lists, trees, etc.
struct str2 {
char c;
int i;
} attribute((packed)) ; // using structure packing
// driver code
int main()
{
Output
Size of str1: 8
Size of str2: 5
Bit Fields
Bit Fields are used to specify the length of the structure members in bits. When we know the
maximum length of the member, we can use bit fields to specify the size and reduce memory
consumption.
// driver code
int main()
{
printf("Size of Str1: %d\nSize of Str2: %d",
sizeof(struct str1), sizeof(struct str2));
return 0;
}
Output
Size of Str1: 8
Size of Str2: 4
As we can see, the size of the structure is reduced when using the bit field to define the max size of the
member ‘a’.
Uses of Structure in C
C structures are used for the following:
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.
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.
Example:
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.
***Note
In C, char* means a pointer to a character. Strings are an array of characters eliminated by the null character
in C.
char* is a pointer to a character, which can be the beginning of a C-string. char* and char[] are used for C-
string and a string object is used for C++ springs. char[] is an array of characters that can be used to store a
C-string.
char[] is a character array whereas char* is a pointer reference. char[] is a specific section of memory in
which we can do things like indexing, whereas char* is the pointer that points to the memory location.
A character array is a sequence of characters, it is the same as a numeric array. A string array contains
pieces of text in it.
The Strcat() function is used to append the whole second string to the first string, whereas the strncat()
function is used to append-only the specific characters of the second string.
***
Syntax:
student[i].member;
Below is the implementation of the above approach:
// C Program to Store Information
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
char* name;
int roll_number;
int age;
double total_marks;
};
// Driver code
int main()
int i = 0, n = 5;
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;
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
Dynamic Memory Allocation in C using malloc(), calloc(), free()
and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes
changing the size of an array. An array is a collection of items stored at contiguous memory
locations.
As can be seen, the length (size) of the array above is 9. But what if there is a requirement to
change this length (size)? For example,
• If there is a situation where only 5 elements are needed to be entered in this array. In this case,
the remaining 4 indices are just wasting memory in this array. So there is a requirement to
lessen the length (size) of the array from 9 to 5.
• Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there
is a need to enter 3 more elements in this array. In this case, 3 indices more are required. So the
length (size) of the array needs to be changed from 9 to 12.
1. malloc()
2. calloc()
3. free()
4. realloc()
C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large
block of memory with the specified size. It returns a pointer of type void which can be cast into a
pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized each
block with the default garbage value initially.
Syntax of malloc() in C
Example of malloc() in C
#include <stdio.h>
#include <stdlib.h>
int main()
int* ptr;
int n, i;
scanf("%d",&n);
if (ptr == NULL) {
exit(0);
else {
// Memory has been successfully allocated
ptr[i] = i + 1;
return 0;
Output
C calloc() method
Syntax of calloc() in C
For Example:
Example of calloc() in C
#include <stdio.h>
#include <stdlib.h>
int main()
int* ptr;
int n, i;
n = 5;
if (ptr == NULL) {
exit(0);
else {
// Memory has been successfully allocated
ptr[i] = i + 1;
return 0;
Output
C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used,
whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by
freeing it.
Syntax of free() in C
free(ptr);
Example of free() in C
#include <stdio.h>
#include <stdlib.h>
int main()
int n, i;
n = 5;
exit(0);
else {
free(ptr);
free(ptr1);
return 0;
Output
C realloc() method
Syntax of realloc() in C
Example of realloc() in C
#include <stdio.h>
#include <stdlib.h>
int main()
int* ptr;
int n, i;
n = 5;
if (ptr == NULL) {
exit(0);
else {
ptr[i] = i + 1;
n = 10;
ptr[i] = i + 1;
free(ptr);
return 0;
Output
#include <stdio.h>
#include <stdlib.h>
int main()
int index = 0, i = 0, n,
int ans;
marks = (int*)malloc(sizeof(
// malloc or not?
if (marks == NULL) {
else {
"using malloc\n");
do {
scanf("%d", &ans);
if (ans == 1) {
index++;
marks = (int*)realloc(
marks,
(index + 1)
* sizeof(
if (marks == NULL) {
else {
printf(
///beginning address of
///allocated memory
marks[i]);
free(marks);
return 0;
Output:
Example:
#include <stdio.h>
#include <stdlib.h>
struct course {
int marks;
char subject[30];
};
int main() {
struct course *ptr;
int noOfRecords;
scanf("%d", &noOfRecords);
printf("Displaying Information:\n");
free(ptr);
return 0;
Output
Displaying Information:
Science 82
DSA 73
The functions malloc() and calloc() are library functions that allocate memory dynamically.
Dynamic means the memory is allocated during runtime (execution of the program) from the heap
segment.
Initialization
malloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of
the block. malloc() doesn’t initialize the allocated memory. If you try to read from the allocated
memory without first initializing it, then you will invoke undefined behavior, which usually means
the values you read will be garbage values.
calloc() allocates the memory and also initializes every byte in the allocated memory to 0. If you
try to read the value of the allocated memory without initializing it, you’ll get 0 as it has already
been initialized to 0 by calloc().
Parameters
Return Value
After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned
otherwise NULL is returned which indicates failure.
Example
The below C code demonstrates the difference between malloc and calloc functions to allocate
dynamic memory.
#include <stdio.h>
#include <stdlib.h>
int main()
// undefined behavior.
// zero.
printf("Values of allocated_with_calloc: ");
putchar('\n');
if (failed_malloc == NULL) {
(void*)failed_malloc);
free(allocated_with_malloc);
free(allocated_with_calloc);
Output
Values of allocated_with_calloc: 0 0 0 0 0
calloc.
malloc() does not add any calloc() adds some extra memory
9. extra memory overhead overhead
Array in C
Structure in C
A structure is a user defined data type in C/C++. A structure creates a data type that can be used to
group items of possibly different types into a single type.
Difference between Structure and Array
ARRAY STRUCTURE
Array uses subscripts or “[ ]” (square bracket) Structure uses “.” (Dot operator) for
for element access element access
Array size is fixed and is basically the number Structure size is not fixed as each element
of elements multiplied by the size of an of Structure can be of different type and
element. size.
Array declaration is done simply using [] and Structure declaration is done with the help
not any keyword. of “struct” keyword.
data_type2 ele2; };
Array elements are stored in contiguous Structure elements may or may not be
memory locations. stored in a contiguous memory location.
Array elements are accessed by their index Structure elements are accessed by their
number using subscripts. names using dot operator.