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

Structure & Dynamic Memory Allocation in C (1)

The document provides a comprehensive overview of structures in C, detailing their declaration, definition, member access, initialization methods, and the use of pointers and nested structures. It also covers advanced topics such as structure padding, packing, and bit fields, along with their applications and limitations. Additionally, it includes examples to illustrate the concepts discussed, making it a useful resource for understanding C structures.

Uploaded by

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

Structure & Dynamic Memory Allocation in C (1)

The document provides a comprehensive overview of structures in C, detailing their declaration, definition, member access, initialization methods, and the use of pointers and nested structures. It also covers advanced topics such as structure padding, packing, and bit fields, along with their applications and limitations. Additionally, it includes examples to illustrate the concepts discussed, making it a useful resource for understanding C structures.

Uploaded by

Aritra Das
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Structure & Dynamic Memory Allocation in C

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>

// create struct with person1 variable


struct Person {
char name[50];
int citNo;
float salary;
} person1;

int main() {

// assign value to name of person1


strcpy(person1.name, "George Orwell");

// assign values to other person1 variables


person1.citNo = 1984;
person1. salary = 2500;

// print struct variables


printf("Name: %s\n", person1.name);
printf("Citizenship No.: %d\n", person1.citNo);
printf("Salary: %.2f", person1.salary);
return 0;
}

Output

Name: George Orwell


Citizenship No.: 1984
Salary: 2500.00

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:

1. Structure Variable Declaration with Structure Template


struct structure_name { data_type
member_name1;data_type
member_name1;
....
....
} variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template


// structure declared beforehand
struct structure_name variable1, variable2, ......................................... ;
Access Structure Members

We can access structure members by using the ( . ) dot operator.

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.

Example of dot(.) Operator

// C program to demonstrate the use of dot operator #include


<stdio.h>

struct str {
int mem;
};

union un {
int mem1;
char mem2;
};

int main()
{
struct str str_name = {
12}; union un un_name;

// accessing union member


un_name.mem1 = 9;
printf("Union Member 1: %d\n", un_name.mem1);

// accessing structure member


printf("Structure Member: %d", str_name.mem);

return 0;
}
Output
Union Member 1: 9
Structure Member: 12

dot(.) operator with Nested Structures and Unions


The dot operator can also be used to access the members of nested structures and unions. It can be
done in the same way as done for the normal structure.
Syntax with Nested Struct
variable_name.member1.member2;

// C program to illustrate the use of dot operator for


// nested structure
#include <stdio.h>

struct base {
struct child {
int i;
} child;
};

int main()
{
struct base s_name = { 12 };

// accessing nested structure member using dot operator


printf("Nested Structure Variable: %d", s_name.child.i);
return 0;
}

Access Structure Members


Syntax:structure_name.member1;
strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the arrow operatorto access
the members.

Initialize Structure Members


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 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.

1. Initialization using Assignment Operator


struct structure_name str;str.member1 =
value1; str.member2 = value2;
str.member3 = value3;
.
.
.

2. 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.

3. Initialization using Designated Initializer List


Designated Initialization allows structure members to be initialized in any order.

struct structure_name str = { .member1 = value1, .member2 = value2,


.member3 = value3 };

// C program to illustrate the use of structures


#include <stdio.h>

// declaring structure with name str1


struct str1 {
int i;
char c;
float f;
char s[30];
};

// declaring structure with name str2


struct str2 {
int ii;
char cc;
float ff;
} var; // variable declaration with structure template

// 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' };

// copying structure using assignment operator

var2 = var1;

printf("Struct 1:\n\ti = %d, c = %c, f = %f, s =


%s\n", var1.i, var1.c, var1.f, var1.s);
printf("Struct 2:\n\ti = %d, c = %c, f = %f, s =
%s\n", var2.i, var2.c, var2.f, var2.s);
printf("Struct 3\n\ti = %d, c = %c, f = %f\n",
var3.ii, var3.cc, var3.ff);

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

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.
// C Program to illustrate the use of typedef with
// structures
#include <stdio.h>

// defining structure
struct str1 {
int a;
};
// defining new name for str1
typedef struct str1 str1;

// another way of using typedef with structures


typedef struct str2 {
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", var2.x);

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() {

// initialize complex variables


num1.comp.imag = 11;
num1.comp.real = 5.25;

// initialize number variable


num1.integer = 6;

// print struct variables


printf("Imaginary Part: %d\n", num1.comp.imag);
printf("Real Part: %.2f\n", num1.comp.real);
printf("Integer: %d", num1.integer);

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:

1. Embedded Structure Nesting


In this method, the structure being nested is also declared inside the parent
structure.
Example

struct parent {

int member1;
struct member_str member2 {int
member_str1;
char member_str2;
...
}
...
}

2. Separate Structure Nesting


In this method, two structures are declared separately and then the member
structure is nested inside the parent structure.
Example

struct member_str { int


member_str1; char
member_str2;
...
}

struct parent { int


member1;
struct member_str member2;
...
}

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;
};

Accessing Nested Members


We can access nested Members by using the same ( . ) dot operator two times as
shown:
str_parent.str_child.member;

Example of Structure Nesting


// C Program to illustrate structure nesting along with
// forward declaration
#include <stdio.h>

// child structure declaration


struct child {
int x;
char c;
};

// parent structure declaration


struct parent {
int a;

struct child b;
};

// driver code
int main()
{
struct parent var1 = { 25, 195, 'A' };

// accessing and printing nested members


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

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.

Example of Structure Pointer

// C program to illustrate the structure pointer


#include <stdio.h>

// 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;

// Accessing structure members using structure pointer

printf("%d %d", ptr->x, ptr->y);

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.

Example of Self-Referential Structures


struct structure_name {
data_type member1;
data_type member2;
struct structure_name* str;
}
// C program to illustrate the self referential structures#include <stdio.h>

// structure templatetypedef
struct str {
int mem1;
int mem2;
struct str* next;
}str;

// driver codeint
main()
{
str var1 = { 1, 2, NULL };

str var2 = { 10, 20, NULL };

// assigning the address of var2 to var1.nextvar1.next = &var2;

// pointer to var1str
*ptr1 = &var1;

// accessing var2 members using var1


printf("var2.mem1: %d\nvar2.mem2: %d", ptr1->next->mem1,ptr1->next-
>mem2);

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.

C Structure Padding and Packing


Technically, the size of the structure in C should be the sum of the sizes of its members. But it may
not be true for most cases. The reason for this is Structure Padding.
Structure padding is the concept of adding multiple empty bytes in the structure to naturally align
the data members in the memory. It is done to minimize the CPU read cycles to retrieve different
data members in the structure.
There are some situations where we need to pack the structure tightly by removing the empty bytes. In
such cases, we use Structure Packing. C language provides two ways for structure packing:
Using #pragma pack(1)
Using attribute((packed))
Example of Structure Padding and Packing
// C program to illustrate structure padding and packing
#include <stdio.h>

// structure with padding


struct str1 {
char c;
int i;
};

struct str2 {
char c;
int i;
} attribute((packed)) ; // using structure packing

// driver code
int main()
{

printf("Size of str1: %d\n", sizeof(struct


str1)); printf("Size of str2: %d\n", sizeof(struct
str2)); return 0;
}

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.

Syntax of Bit Fields


struct structure_name {
data_type member_name: width_of_bit-field;
};
Example of Bit Fields
// C Program to illustrate bit fields in structures
#include <stdio.h>

// declaring structure for reference


struct str1 {
int a;
char c;
};

// structure with bit fields


struct str2 {
int a : 24; // size of 'a' is 3 bytes = 24 bits
char c;
};

// 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:

C Program to Store Information of Students Using Structure


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. 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.
Syntax:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};

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.
***Note

What does char* [] mean in C?

In C, char* means a pointer to a character. Strings are an array of characters eliminated by the null character
in C.

Is char* the same as string?

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.

What is the difference between char and char*?

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.

What is a character array?

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.

What is the difference between Strcat and Strncat?

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.

Which argument does the strcat() function take?

The strcat() function takes two arguments: src and dest.

***
Syntax:
student[i].member;
Below is the implementation of the above approach:
// 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
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.

This procedure is referred to as Dynamic Memory Allocation in C.


Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a
data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C
defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming.
They are:

1. malloc()

2. calloc()

3. free()

4. realloc()

Let’s look at each of them in greater detail.

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

ptr = (cast-type*) malloc(byte-size)


For Example:

ptr = (int*) malloc(100 * sizeof(int));


Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer
ptr holds the address of the first byte in the allocated memory.
If space is insufficient, allocation fails and returns a NULL pointer.

Example of malloc() in C

#include <stdio.h>

#include <stdlib.h>

int main()

// This pointer will hold the

// base address of the block created

int* ptr;

int n, i;

// Get the number of elements for the array

printf("Enter number of elements:");

scanf("%d",&n);

printf("Entered number of elements: %d\n", n);

// Dynamically allocate memory using malloc()

ptr = (int*)malloc(n * sizeof(int));

// Check if the memory has been successfully

// allocated by malloc or not

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {
// Memory has been successfully allocated

printf("Memory successfully allocated using malloc.\n");

// Get the elements of the array

for (i = 0; i < n; ++i) {

ptr[i] = i + 1;

// Print the elements of the array

printf("The elements of the array are: ");

for (i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

return 0;

Output

Enter number of elements: 5

Memory successfully allocated using malloc.

The elements of the array are: 1, 2, 3, 4, 5,

C calloc() method

1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified


number of blocks of memory of the specified type. it is very much similar to malloc() but has
two different points and these are:

2. It initializes each block with a default value ‘0’.

3. It has two parameters or arguments as compare to malloc().

Syntax of calloc() in C

ptr = (cast-type*)calloc(n, element-size);


here, n is the no. of elements and element-size is the size of each element.

For Example:

ptr = (float*) calloc(25, sizeof(float));


This statement allocates contiguous space in memory for 25 elements each with the size of the
float.
If space is insufficient, allocation fails and returns a NULL pointer.

Example of calloc() in C

#include <stdio.h>

#include <stdlib.h>

int main()

// This pointer will hold the

// base address of the block created

int* ptr;

int n, i;

// Get the number of elements for the array

n = 5;

printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()

ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully

// allocated by calloc or not

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {
// Memory has been successfully allocated

printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array

for (i = 0; i < n; ++i) {

ptr[i] = i + 1;

// Print the elements of the array

printf("The elements of the array are: ");

for (i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

return 0;

Output

Enter number of elements: 5

Memory successfully allocated using calloc.

The elements of the array are: 1, 2, 3, 4, 5,

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()

// This pointer will hold the

// base address of the block created

int *ptr, *ptr1;

int n, i;

// Get the number of elements for the array

n = 5;

printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()

ptr = (int*)malloc(n * sizeof(int));

// Dynamically allocate memory using calloc()

ptr1 = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not

if (ptr == NULL || ptr1 == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {

// Memory has been successfully allocated

printf("Memory successfully allocated using malloc.\n");

// Free the memory

free(ptr);

printf("Malloc Memory successfully freed.\n");

// Memory has been successfully allocated

printf("\nMemory successfully allocated using calloc.\n");

// Free the memory

free(ptr1);

printf("Calloc Memory successfully freed.\n");

return 0;

Output

Enter number of elements: 5

Memory successfully allocated using malloc.

Malloc Memory successfully freed.

Memory successfully allocated using calloc.

Calloc Memory successfully freed.

C realloc() method

“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of


a previously allocated memory. In other words, if the memory previously allocated with the help of
malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-
allocation of memory maintains the already present value and new blocks will be initialized with
the default garbage value.

Syntax of realloc() in C

ptr = realloc(ptr, newSize);


where ptr is reallocated with new size 'newSize'.

If space is insufficient, allocation fails and returns a NULL pointer.

Example of realloc() in C

#include <stdio.h>

#include <stdlib.h>

int main()

// This pointer will hold the

// base address of the block created

int* ptr;

int n, i;

// Get the number of elements for the array

n = 5;

printf("Enter number of elements: %d\n", n);


// Dynamically allocate memory using calloc()

ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully

// allocated by malloc or not

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {

// Memory has been successfully allocated

printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array

for (i = 0; i < n; ++i) {

ptr[i] = i + 1;

// Print the elements of the array

printf("The elements of the array are: ");

for (i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

// Get the new size for the array

n = 10;

printf("\n\nEnter the new size of the array: %d\n", n);

// Dynamically re-allocate memory using realloc()

ptr = (int*)realloc(ptr, n * sizeof(int));

// Memory has been successfully allocated

printf("Memory successfully re-allocated using realloc.\n");

// Get the new elements of the array


for (i = 5; i < n; ++i) {

ptr[i] = i + 1;

// Print the elements of the array

printf("The elements of the array are: ");

for (i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

free(ptr);

return 0;

Output

Enter number of elements: 5

Memory successfully allocated using calloc.

The elements of the array are: 1, 2, 3, 4, 5,

Enter the new size of the array: 10

Memory successfully re-allocated using realloc.

The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

One another example for realloc() method is:

#include <stdio.h>

#include <stdlib.h>

int main()

int index = 0, i = 0, n,

*marks; // this marks pointer hold the base address

// of the block created

int ans;

marks = (int*)malloc(sizeof(

int)); // dynamically allocate memory using malloc


// check if the memory is successfully allocated by

// malloc or not?

if (marks == NULL) {

printf("memory cannot be allocated");

else {

// memory has successfully allocated

printf("Memory has been successfully allocated by "

"using malloc\n");

printf("\n marks = %pc\n",

marks); // print the base or beginning

// address of allocated memory

do {

printf("\n Enter Marks\n");

scanf("%d", &marks[index]); // Get the marks

printf("would you like to add more(1/0): ");

scanf("%d", &ans);

if (ans == 1) {

index++;

marks = (int*)realloc(

marks,

(index + 1)

* sizeof(

int)); // Dynamically reallocate

// memory by using realloc

// check if the memory is successfully

// allocated by realloc or not?

if (marks == NULL) {

printf("memory cannot be allocated");

else {

printf("Memory has been successfully "

"reallocated using realloc:\n");

printf(

"\n base address of marks are:%pc",


marks); ////print the base or

///beginning address of

///allocated memory

} while (ans == 1);

// print the marks of the students

for (i = 0; i <= index; i++) {

printf("marks of students %d are: %d\n ", i,

marks[i]);

free(marks);

return 0;

Output:

Example:

C Program to Store Data in Structures Dynamically

#include <stdio.h>

#include <stdlib.h>

struct course {

int marks;

char subject[30];

};

int main() {
struct course *ptr;

int noOfRecords;

printf("Enter the number of records: ");

scanf("%d", &noOfRecords);

// Memory allocation for noOfRecords structures

ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));

for (int i = 0; i < noOfRecords; ++i) {

printf("Enter subject and marks:\n");

scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);

printf("Displaying Information:\n");

for (int i = 0; i < noOfRecords; ++i) {

printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);

free(ptr);

return 0;

Output

Enter the number of records: 2


Enter subject and marks:
Science 82
Enter subject and marks:
DSA 73

Displaying Information:
Science 82
DSA 73

Difference Between malloc() and calloc() with Examples

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

malloc() takes a single argument, which is the number of bytes to allocate.

Unlike malloc(), calloc() takes two arguments:

1. Number of blocks to be allocated.

2. Size of each block in bytes.

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.

// C code that demonstrates the difference

// between calloc and malloc

#include <stdio.h>

#include <stdlib.h>

int main()

// Both of these allocate the same number of bytes,

// which is the amount of bytes that is required to

// store 5 int values.

// The memory allocated by calloc will be

// zero-initialized, but the memory allocated with

// malloc will be uninitialized so reading it would be

// undefined behavior.

int* allocated_with_malloc = malloc(5 * sizeof(int));

int* allocated_with_calloc = calloc(5, sizeof(int));

// As you can see, all of the values are initialized to

// zero.
printf("Values of allocated_with_calloc: ");

for (size_t i = 0; i < 5; ++i) {

printf("%d ", allocated_with_calloc[i]);

putchar('\n');

// This malloc requests 1 terabyte of dynamic memory,

// which is unavailable in this case, and so the

// allocation fails and returns NULL.

int* failed_malloc = malloc(1000000000000);

if (failed_malloc == NULL) {

printf("The allocation failed, the value of "

"failed_malloc is: %p",

(void*)failed_malloc);

// Remember to always free dynamically allocated memory.

free(allocated_with_malloc);

free(allocated_with_calloc);

Output

Values of allocated_with_calloc: 0 0 0 0 0

The allocation failed, the value of failed_malloc is: (nil)

Difference between malloc() and calloc() in C

S.No. malloc() calloc()

malloc() is a function that calloc() is a function that assigns a


creates one block of specified number of blocks of
1. memory of a fixed size. memory to a single variable.

malloc() only takes one


calloc() takes two arguments.
2. argument

3. malloc() is faster than calloc() is slower than malloc()


S.No. malloc() calloc()

calloc.

malloc() has high time


calloc() has low time efficiency
4. efficiency

malloc() is used to indicate calloc() is used to indicate


5. memory allocation contiguous memory allocation

Syntax : void* malloc(size_t Syntax : void* calloc(size_t num,


6. size); size_t size);

malloc() does not initialize calloc() initializes the memory to


8. the memory to zero zero

malloc() does not add any calloc() adds some extra memory
9. extra memory overhead overhead

Difference between Structure and Array in C

Array in C

An array is collection of items stored at contiguous memory locations.

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 refers to a collection consisting of Structure refers to a collection consisting


elements of homogeneous data type. of elements of heterogeneous data type.

Array uses subscripts or “[ ]” (square bracket) Structure uses “.” (Dot operator) for
for element access element access

Array is pointer as it points to the first element


Structure is not a pointer
of the collection.

Instantiation of Structure objects is


Instantiation of Array objects is not possible.
possible.

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.

Bit field is not possible in an Array. Bit field is possible in an Structure.

Array declaration is done simply using [] and Structure declaration is done with the help
not any keyword. of “struct” keyword.

Arrays is a non-primitive datatype Structure is a user-defined datatype.

Structure traversal and searching is


Array traversal and searching is easy and fast.
complex and slow.

data_type array_name[size]; struct sruct_name{ data_type1 ele1;


ARRAY STRUCTURE

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.

You might also like