Professional Documents
Culture Documents
06. Structures and Dynamic Memory
06. Structures and Dynamic Memory
Structure using typedef: typedef is a keyword that is used to assign a new name to any existing
data-type. Below is the C++ program illustrating use of struct using typedef:
// Declaration of typedef
typedef struct GeekForGeeks {
int G1;
char G2;
float G3;
} GFG;
// Driver Code
int main()
{
GFG Geek;
Geek.G1 = 85;
Geek.G2 = 'G';
Geek.G3 = 989.45;
return 0;
}
Output
The value is : 85
The value is : G
The value is : 989.45
Explanation:
In the above code, the keyword “typedef” is used before struct and after the closing bracket of
structure, “GFG” is written.
Now create structure variables without using the keyword “struct” and the name of the struct.
A structure instance has been created named “Geek” by just writing “GFG” before it.
C++ Unions
In C++, a union is a user-defined datatype in which we can define members of different types of data
types just like structures. But one thing that makes it different from structures is that the member
variables in a union share the same memory location, unlike a structure that allocates memory
separately for each member variable. The size of the union is equal to the size of the largest data type.
Memory space can be used by one member variable at one point in time, which means if we assign
value to one member variable, it will automatically deallocate the other member variable stored in the
memory which will lead to loss of data.
union Union_Name {
// Declaration of data members
}; union_variables;
After defining the union we can also create an instance of it the same as we create an object of
int main(){
union Union_Name var1;
// or
Union_Name var1;
}
Enumeration in C++
Enumeration (Enumerated type) is a user-defined data type that can be assigned some limited values.
These values are defined by the programmer at the time of declaring the enumerated type.
If we assign a float value to a character value, then the compiler generates an error. In the same way,
if we try to assign any other value to the enumerated data types, the compiler generates an error.
Enumerator types of values are also known as enumerators.
// C++ Program to Demonstrate the Functioning of Enumerators
// with an Example of Year
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
int i;
return 0;
}
typedef in C++
typedef keyword in C++ is used for aliasing existing data types, user-defined data types, and pointers
to a more meaningful name.
Mostly typedefs are used for aliasing, only if the predefined name is too long or complex to write again
and again.
Applications of typedef in C++
typedef in C++ can be used for aliasing predefined data types with long names.
It can be used with STL data structures like Vectors, Strings, Maps, etc.
typedef can be used with arrays as well.
We can use typedef with normal pointers as well as function pointers.
struct StructName {
dataType fieldName : width;
// more bit-field members...
};
class ClassName {
public:
dataType fieldName : width;
// more bit-field members...
};
Note: It is to be noted that bit fields are only acceptable for integral data types.
Only data members are allowed, it cannot Can hold both: member functions and data
have member functions. members.
Writing the ‘struct’ keyword is necessary to Writing the ‘struct’ keyword is not necessary to
declare structure-type variables. declare structure-type variables.
Sizeof operator will generate 0 for an empty Sizeof operator will generate 1 for an empty
structure. structure.
int main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for above error is simple, when a datatype is declared, no memory is allocated for it.
Memory is allocated only when variables are created.
Structure members can be initialized with declaration in C++. For Example the following C++
program Executes Successfully without throwing any Error.
// In C++ We can Initialize the Variables with Declaration in Structure.
#include <iostream>
using namespace std;
struct Point {
int x = 0; // It is Considered as Default Arguments and no Error is Raised
int y = 1;
};
int main()
{
struct Point p1;
Output
x=0, y=1
x=0, y=20
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.
There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic
memory allocation in C programming. They are:
malloc()
calloc()
free()
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
ptr = (cast-type*) malloc(byte-size)
C calloc() method
“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:
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.
Syntax of free() in C
free(ptr);
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.
new operator
The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is
available, a new operator initializes the memory and returns the address of the newly allocated and
initialized memory to the pointer variable.
Initialize memory:
pointer-variable = new data-type(value);
delete operator
delete pointer-variable: Eg: delete p;
delete[] pointer-variable: Eg: delete[] p;
malloc() vs new():
malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific
for C++ only.
Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call
the constructor of a class whereas “malloc()” does not.
free() vs delete:
free() is a C library function that can also be used in C++, while “delete” is a C++ keyword.
free() frees memory but doesn’t call Destructor of a class whereas “delete” frees the memory and
also calls the Destructor of the class.
Typical Use When you have a direct instance When you have a pointer to an
Case of a structure or class instance of a structure or class
Feature Dot (.) Operator Arrow (->) Operator
Instead of managing memory manually, try to use smart pointers where applicable.
use std::string instead of char *. The std::string class handles all memory management internally,
and it’s fast and well-optimized.
Allocate memory by new keyword and deallocate memory by delete keyword and write all code
between them.
Static Memory Allocation is done before Dynamic Memory Allocation is done during
program execution. program execution.
It uses stack for managing the static It uses heap for managing the dynamic allocation
allocation of memory. of memory
In this memory is allocated at compile time. In this memory is allocated at run time.
In this allocated memory remains from start In this allocated memory can be released at any
to end of the program. time during the program.
Example: This static memory allocation is Example: This dynamic memory allocation is
generally used for array. generally used for linked list.