Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use use an array of pointers (Jagged) in C/C++?
In C programming, an array of pointers (also known as jagged arrays) allows you to store multiple pointers in a single array. This is particularly useful when working with strings of different lengths or when you need to point to different memory locations dynamically.
Syntax
data_type *array_name[size];
Where data_type is the type of data the pointers will point to, and size is the number of pointers the array can hold.
Example 1: Array of Integer Pointers
The following example demonstrates how to create an array of pointers that point to integer values −
#include <stdio.h>
const int MAX = 3;
int main() {
int var[] = {10, 100, 200};
int *ptr[MAX];
int i;
/* Assign addresses of integers to pointer array */
for (i = 0; i < MAX; i++) {
ptr[i] = &var[i];
}
/* Access values through pointer array */
for (i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i]);
}
return 0;
}
Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200
Example 2: Array of Character Pointers (Strings)
Arrays of character pointers are commonly used to store multiple strings efficiently −
#include <stdio.h>
const int MAX = 4;
int main() {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
int i;
for (i = 0; i < MAX; i++) {
printf("Value of names[%d] = %s\n", i, names[i]);
}
return 0;
}
Value of names[0] = Zara Ali Value of names[1] = Hina Ali Value of names[2] = Nuha Ali Value of names[3] = Sara Ali
Example 3: Dynamic Memory Allocation with Pointer Arrays
You can also use pointer arrays with dynamically allocated memory −
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr[3];
int values[] = {25, 50, 75};
int i;
/* Allocate memory and assign values */
for (i = 0; i < 3; i++) {
ptr[i] = (int*)malloc(sizeof(int));
if (ptr[i] != NULL) {
*ptr[i] = values[i];
}
}
/* Display values */
for (i = 0; i < 3; i++) {
if (ptr[i] != NULL) {
printf("Value %d: %d\n", i, *ptr[i]);
}
}
/* Free allocated memory */
for (i = 0; i < 3; i++) {
if (ptr[i] != NULL) {
free(ptr[i]);
}
}
return 0;
}
Value 0: 25 Value 1: 50 Value 2: 75
Key Points
- Each element in a pointer array stores a memory address, not the actual value.
- Use the dereference operator (*) to access the value at the address.
- Pointer arrays are memory-efficient for storing strings of varying lengths.
- Always check for NULL when using dynamic memory allocation.
- Remember to free dynamically allocated memory to prevent memory leaks.
Conclusion
Array of pointers in C provides flexibility for handling multiple data elements efficiently. They are particularly useful for string arrays and dynamic memory management, offering better memory utilization compared to traditional 2D arrays.
