Write a C Program using pointers to read an array of integers
Illustration of dynamic memory allocation using malloc() in C , array of integers #c language tutorial
Working with pointers in C is essential for efficient memory management and dynamic data structures. In this tutorial, we will write a C program using pointers to read and display an array of integers. This program dynamically allocates memory for the array using malloc(), ensuring flexibility in handling different array sizes.
By the end of this guide, you will:
✅ Understand how to use pointers to handle arrays in C.
✅ Learn dynamic memory allocation using malloc().
✅ Implement efficient array manipulation with pointers.
Here’s the complete C program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, i, n;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamic memory allocation
ptr = (int *)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed!");
return 1;
}
// Input elements using pointers
for (i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", ptr + i);
}
// Displaying elements using pointers
printf("\nThe entered array elements are: ");
for (i = 0; i < n; i++) {
printf("%d ", *(ptr + i));
}
// Free allocated memory
free(ptr);
return 0;
}
Instead of declaring a fixed-size array, we use malloc() to allocate memory dynamically:
ptr = (int *)malloc(n * sizeof(int));
This allows the program to handle different input sizes efficiently.
We use pointer arithmetic to store and retrieve elements:
ptr + i points to the memory location of the i-th element.*(ptr + i) accesses the value stored at that memory location.
After using the dynamically allocated memory, we free it using free(ptr), preventing memory leaks.
✅ Efficient Memory Management: Allocates memory dynamically, avoiding waste.
✅ Faster Execution: Direct memory access speeds up operations.
✅ Flexible Data Structures: Helps in implementing linked lists, trees, and dynamic arrays.
🔴 Forgetting to check malloc() return value → Always verify if memory allocation was successful.
🔴 Not using free(ptr) → Can cause memory leaks, so always free allocated memory.
🔴 Using ptr[i] instead of *(ptr + i) → Both work, but *(ptr + i) emphasizes pointer arithmetic.
This guide covered how to read an array using pointers in C, dynamically allocate memory, and display elements efficiently. Mastering C pointer manipulation is a crucial step for improving programming skills.