Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Syntax
1.2.
Example
1.3.
C++
2.
Array of Pointers to Character
2.1.
Syntax
2.2.
Example
2.3.
C++
3.
Array of Pointers to Different Types
3.1.
Syntax
3.2.
Example
3.3.
C
4.
Application of Array of Pointers
5.
Disadvantages of Array of Pointers
6.
Frequently Asked Questions
6.1.
Can we have an array of pointers to different data types in C?
6.2.
How do we access the elements pointed to by an array of pointers?
6.3.
What is the difference between an array of pointers and a pointer to an array?
7.
Conclusion
Last Updated: Jul 13, 2024
Easy

Array of Pointers in C

Author Rinki Deka
0 upvote

Introduction

An array of pointers in C is a way to store and work with a collection of pointers. It allows you to create an array where each element is a pointer to another variable or array. This is useful when you must keep track of many variables or create complex data structures. 

Array of Pointers in C

In this article, we will learn about the syntax for creating an array of pointers, see examples of arrays of pointers to characters and other types, understand their applications, and discuss their disadvantages.

Syntax

The syntax for creating an array of pointers in C is straightforward. Here's how you declare an array of pointers:

data_type *array_name[array_size];


In this declaration, data_type is the type of data the pointers will point to, array_name is the name you give to your array, and array_size is the number of pointers the array will hold.

For example, to create an array of 5 pointers to integers, you would write:

int *ptr_array[5];


This creates an array named ptr_array that can store 5 pointers to integer variables.

Example

Suppose we want to store the addresses of 5 integer variables in an array of pointers.

  • C++

C++

#include <stdio.h>

int main() {

   int num1 = 10, num2 = 20, num3 = 30, num4 = 40, num5 = 50;

   int *ptr_array[5];   

   ptr_array[0] = &num1;

   ptr_array[1] = &num2;

   ptr_array[2] = &num3;

   ptr_array[3] = &num4;

   ptr_array[4] = &num5;

   for (int i = 0; i < 5; i++) {

       printf("Value of num%d: %d\n", i+1, *ptr_array[i]);

   }   

   return 0;

}

In this example, we declare 5 integer variables num1 to num5. We then create an array ptr_array of 5 pointers to integers. We assign the addresses of the integer variables to the elements of the ptr_array using the & operator.

Finally, we use a for loop to print the values stored at each address in ptr_array. The * operator is used to dereference the pointers and access the values.

Output:

Value of num1: 10
Value of num2: 20
Value of num3: 30
Value of num4: 40
Value of num5: 50


This example demonstrates how an array of pointers can store and access multiple variables' addresses

Array of Pointers to Character

An array of pointers to characters is commonly used in C for working with strings. Instead of storing the characters directly, an array of pointers stores the addresses of the first character of each string.

Syntax

char *str_array[array_size];


Here, str_array is an array that can hold array_size number of pointers to characters.

Example

Let's see an example where we store multiple strings using an array of pointers to characters.

  • C++

C++

#include <stdio.h>

int main() {

   char *names[] = {"Rahul", "Rinki", "Harsh", "Sanjana", "Ravi"};

   int size = sizeof(names) / sizeof(names[0]);   

   printf("Names:\n");

   for (int i = 0; i < size; i++) {

       printf("%s\n", names[i]);

   }   

   return 0;

}


In this example, we declare an array names of pointers to characters and initialize it with string literals. The sizeof operator is used to calculate the number of elements in the array.

We then use a for loop to print each string stored in the names array. Since each element of names is a pointer to a character (i.e., a string), we can directly use the %s format specifier to print the strings.

Output

Names:
Rahul
Rinki
Harsh
Sanjana
Ravi

Array of Pointers to Different Types

In C, you can create an array of pointers to different data types. This allows you to store pointers to variables of various types in a single array.

Syntax

void *ptr_array[array_size];


Here, ptr_array is an array of array_size pointers to void. The void pointer can hold the address of any data type.

Example

Let's see an example where we create an array of pointers to different data types.

  • C

C

#include <stdio.h>

int main() {

   int num = 10;

   float fnum = 3.14;

   char ch = 'A';

   void *ptr_array[3];   

   ptr_array[0] = &num;

   ptr_array[1] = &fnum;

   ptr_array[2] = &ch;   

   printf("Integer value: %d\n", *(int *)ptr_array[0]);

   printf("Float value: %.2f\n", *(float *)ptr_array[1]);

   printf("Character value: %c\n", *(char *)ptr_array[2]);

  

   return 0;

}


In this example, we declare variables of different types: num (integer), fnum (float), and ch (character). We create an array ptr_array of 3 pointers to void.

We assign the addresses of num, fnum, and ch to the elements of ptr_array.

To access the values stored at each address, we use explicit type casting. We cast the void pointers to the appropriate data type using (int *), (float *), and (char *) before dereferencing them with the * operator.

Output:

Integer value: 10
Float value: 3.14
Character value: A


This example demonstrates how an array of pointers to void can be used to store pointers to different data types. However, it is important to keep track of the actual data type each pointer points to and use appropriate type casting when accessing the values.

Application of Array of Pointers

Arrays of pointers have various applications in C programming which are :

  1. Storing and manipulating strings: As we saw earlier, an array of pointers to characters is frequently used to store and work with multiple strings efficiently.
     
  2. Implementing data structures: Arrays of pointers are used in the implementation of data structures like linked lists, trees, and graphs. Each element of the array can store the address of a node or structure, allowing efficient traversal and manipulation of the data structure.
     
  3. Function pointers: An array of pointers to functions can be used to store and call multiple functions dynamically based on user input or certain conditions.
     
  4. Command-line arguments: When a C program is executed with command-line arguments, the argv parameter of the main function is an array of pointers to characters. It stores the command-line arguments passed to the program.
     
  5. Dynamically allocating memory: An array of pointers can be used to dynamically allocate memory for multiple variables or structures. Each pointer in the array can point to a dynamically allocated block of memory.
     
  6. Lookup tables: Arrays of pointers can be used to create lookup tables where each element of the array points to a corresponding value or structure. This allows for efficient retrieval of data based on a given index or key.

Disadvantages of Array of Pointers

Here are a few disadvantages of using arrays of pointers:

  1. Complexity: Using arrays of pointers can add complexity to the code. It requires careful management of memory allocation and deallocation, as well as proper handling of pointers to avoid dangling pointers or memory leaks.
     
  2. Lack of type safety: When using an array of pointers to void or casting pointers to different types, there is a lack of type safety. The compiler cannot catch type-related errors at compile-time, making the code more prone to runtime errors if not handled correctly.
     
  3. Difficulty in debugging: Debugging code that heavily relies on arrays of pointers can be challenging. Issues like incorrect pointer arithmetic, memory corruption, or accessing invalid memory addresses can be hard to identify and fix.
     
  4. Increased memory usage: Each pointer in an array of pointers requires additional memory to store the address. If the number of pointers is large, it can lead to increased memory consumption compared to using arrays of actual values.
     
  5. Reduced cache performance: When accessing elements through an array of pointers, the memory accesses may not be contiguous. This can lead to reduced cache performance and slower execution compared to accessing elements in a contiguous memory layout.
     
  6. Readability and maintainability: Code that extensively uses arrays of pointers can be harder to read and understand, especially for developers who are not familiar with the codebase. This can impact the maintainability of the code in the long run.

Frequently Asked Questions

Can we have an array of pointers to different data types in C?

Yes, by using an array of pointers to void and explicit type casting, we can store pointers to different data types in a single array.

How do we access the elements pointed to by an array of pointers?

To access the elements pointed to by an array of pointers, we use the * operator to dereference the pointer and access the value it points to.

What is the difference between an array of pointers and a pointer to an array?

An array of pointers is a collection of pointers stored in an array, while a pointer to an array is a single pointer that points to the first element of an array.

Conclusion

In this article, we learned about arrays of pointers in C. We talked about the syntax for declaring an array of pointers and saw examples of arrays of pointers to characters and different data types. We also discussed the various applications of arrays of pointers, such as storing strings, implementing data structures, and handling command-line arguments. Additionally, we covered some disadvantages of using arrays of pointers like, complexity, lack of type safety, and potential impacts on performance and maintainability. 

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass