Arrays and Dynamic Memory Allocation
Arrays and Dynamic Memory Allocation
Example:
int *ptr;
ptr = (int*) malloc(100 * sizeof(int));
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using malloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
free(ptr);
return 0;
}
The “calloc” or “contiguous allocation” method in C is used to
dynamically allocate the specified number of blocks of memory of the
specified type. It initializes each block with a default value ‘0’.
Example:
float *ptr;
ptr = (float*) calloc(25, sizeof(float));
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
free(ptr);
return 0;
}
//sum of array elements using pointers
#include <stdio.h>
#include <malloc.h>
int main() {
int i, n, sum = 0;
int *ptr;
printf("Enter size of array : ");
scanf("%d", &n);
ptr = (int *)malloc(n * sizeof(int));
printf("Enter elements in the List ");
for (i = 0; i < n; i++) {
scanf("%d", ptr + i);
}
//calculate sum of elements
for (i = 0; i < n; i++) {
sum = sum + *(ptr + i);
}
printf("\n Sum of all elements in an array is = %d\n", sum);
free(ptr);
return 0;
A two-dimensional array of pointers can also be created using
Dynamic Memory Allocation. We can use the malloc() function to
dynamically allocate memory.
#include <stdio.h>
#include <stdlib.h>
int main() {
int arr1[5][5] = { { 0, 1, 2, 3, 4 },
{ 2, 3, 4, 5, 6 },
{ 4, 5, 6, 7, 8 },
{ 5, 4, 3, 2, 6 },
{ 2, 5, 4, 3, 1 } };
#include <stdio.h>
int main() {
int arr1[5][5] = { { 0, 1, 2, 3, 4 },
{ 2, 3, 4, 5, 6 },
{ 4, 5, 6, 7, 8 },
{ 5, 4, 3, 2, 6 },
{ 2, 5, 4, 3, 1 } };
int* arr2[5][5];
// Initializing each element of the pointer array with the address of
element present in the other array
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
arr2[i][j] = &arr1[i][j];
}
}
// Printing the array using the array of pointers
printf("The values are\n");
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
printf("%d ", *arr2[i][j]);
}
printf("\n");
}
return 0;
}