Alternative of Malloc in C
An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used for storing similar types of elements as the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C or C++ can store derived data types such as the structures, pointers, etc. Given below is the picturesque representation of an array.
There are two types of array/ string declaration in C++ as listed as follows
- Static Declaration
- Dynamic Declaration
Way 1: Static Declaration
Methods: The static declaration can be done in 3 ways
- Array declaration by specifying the size
- Array declaration by initializing the elements
- Array declaration by specifying the size and initializing elements
Array declaration by specifying the size
Syntax:
int arr1[10];
// Array declaration by specifying size
int n = 10;
int arr2[n];
Note: With recent C/C++ versions, we can also declare an array of user-specified size
Array declaration by initializing the elements
int arr[] = {10, 20, 30, 40};
// Array declaration by initializing elements
Compiler creates an array of size 4. This is same as “int arr[4] = {10, 20, 30, 40}”
Array declaration by specifying the size and initializing elements
Syntax:
int arr[6] = {10, 20, 30, 40} ;
// Array declaration by specifying size
// and initializing elements
Compiler creates an array of size 6, initializes first 4 elements as specified by user and rest two elements as above is same as follows:
int arr[] = {10, 20, 30, 40, 0, 0}"
Note: In a static declaration, the memory will get allocated in the stack memory.
Implementation: Below is the C program to demonstrate static declaration
Example 1:
C
#include <stdio.h>
int main()
{
int first_array[2];
first_array[0] = 10;
first_array[1] = 20;
printf ( "%d %d" , first_array[0],
first_array[1]);
return 0;
}
|
Dynamic declaration: Malloc is used for dynamically allocating an array. In this situation, the memory will be allocated in heap. Allocated memory will get free after completion of the program.
Example 2:
C
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *first_array = ( int *) malloc ( sizeof ( int )*2);
first_array[0] = 10;
first_array[1] = 20;
printf ( "%d %d" , first_array[0],
first_array[1]);
return 0;
}
|
Now coming to the eccentric goal in figuring an alternative way to allocate the memory instead of Dynamic declaration
Example 3:
C
#include<stdio.h>
int main()
{
int *first_array = ( int [2]){};
first_array[0] = 10;
first_array[1] = 20;
printf ( "%d %d" , first_array[0],
first_array[1]);
return 0;
}
|
Last Updated :
28 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...