top

Search

C Tutorial

.

UpGrad

C Tutorial

Array of Pointers in C

Mastering arrays and pointers can be a daunting challenge for novice programmers, especially in a powerful language like C. The core of this task involves understanding the dynamic nature of C and the essence of its memory manipulation functionality. This article will guide you through the basics and intricacies of the array of pointer in C, with a hands-on array of pointers with example to enhance your understanding. Explore the benefits and limitations of using an array of pointers, their applications, and syntax.

Introduction

To begin, let's demystify the array of pointers in C. Simply put, an array of pointers is a collection of memory addresses, each holding the location of different variables. Each element of the array points to the address of a variable. It provides flexibility and efficiency when working with arrays and data structures, allowing for more dynamic data manipulation.

Advantages of Array of Pointers

Understanding the advantages of the array of pointers in C enables programmers to fully leverage this functionality. Let's delve into the key benefits that arrays of pointers offer:

1. Memory Efficiency: An array of pointers has an edge over traditional 2D arrays when it comes to memory usage. While a 2D array requires a contiguous block of memory, an array of pointers allocates memory for each row independently, thus only consuming what is necessary. This difference can be significant, particularly when working with large arrays.

2. Flexibility: Flexibility in terms of array size is another significant advantage that an array of pointers offers. Unlike static arrays, where the size needs to be defined at compile-time, an array of pointers enables the creation and manipulation of dynamic arrays whose size can be changed at runtime.

3. Better Memory Access: As pointers provide direct access to memory addresses, operations involving them are usually faster. Programs using pointers for memory access tend to be more efficient than their counterparts that indirectly access memory.

Disadvantages of Array of Pointers

Despite the numerous advantages of using an array of pointers in C, there are certain caveats to keep in mind. While this concept is a powerful tool in a programmer's arsenal, like any tool, it has disadvantages and must be handled carefully. Let's explore the pitfalls that can come with using an array of pointer in C:

1. Complexity: The use of pointers, especially arrays of pointers, can make code more complex and harder to understand. It's not uncommon for programmers, especially beginners, to find pointers confusing. This can increase the learning curve for new coders and add difficulty in reading and maintaining the code.

2. Risk of Errors: Pointers are powerful tools, but with that power comes the potential for significant errors. Improper manipulation of pointers can lead to a variety of issues. For instance, dereferencing uninitialised pointers can lead to segmentation faults, while failure to free memory allocated dynamically can result in memory leaks. These issues underscore the need for meticulous memory management when working with pointers.

Application of Array of Pointers

The array of pointer in C has broad applications, particularly in handling and manipulating data. Understanding these applications can offer powerful perspectives on how this tool can be used effectively in real-world scenarios.

1. Handling Strings and Text: A prevalent use case of arrays of pointers is in managing strings of text. For instance, an array of pointers can be used to store a collection of strings with varying lengths. This application is more memory efficient than a two-dimensional character array, particularly when the lengths of strings significantly differ.
Consider the example of storing names of different lengths. Using an array of pointers, each name is stored only once, and pointers are used to reference them. This reduces the unnecessary waste of memory space, which would be the case if a 2D character array was used.

2. Implementing Data Structures: Arrays of pointers are critical in implementing complex data structures. For instance, trees and graphs often make use of arrays of pointers to manage nodes. Each element in the array serves as a pointer to a different node, which can be manipulated directly using the corresponding pointer.

3. Creating Multi-Dimensional Arrays: In scientific computing and game development, multi-dimensional arrays are often used to represent physical space or grids. However, these domains often require non-uniform structures, which are difficult to achieve with traditional multi-dimensional arrays. An array of pointers offers a flexible and memory-efficient solution to this issue by allowing each sub-array to have a different length.

4. Managing Large Data Sets: In databases and large-scale data processing, arrays of pointers are often used to manage large data sets. Pointers allow for more efficient memory usage and faster data access. Instead of moving data around in memory, pointers can be used to access and manipulate data directly, resulting in significant performance benefits.

Relationship between Pointers and Arrays in C

Grasping the relationship between pointers and arrays in C is fundamental to mastering this language. To put it simply, arrays and pointers in C are inextricably linked. How so? An array can be seen as a constant pointer, pointing to its first element.

Let's break down this idea:

When you declare an array, say int arr[5];, you're reserving space in memory for five integers. The variable arr is a constant pointer to the first element of the array, arr[0]. So if you were to print arr, you would get the memory address of the first element, arr[0].

But how does this tie in with pointer arithmetic and accessing array elements?

When you write arr[i] to access the i-th element of an array, it's the same as writing *(arr + i). In the latter, arr is the base address, and you're adding i times the size of the data type. In the case of int arr[5];, you're adding i times the size of an integer to the base address. The result is the address of the i-th element, and the * operator is used to dereference this address and get the value stored there.

Here's an example to illustrate:

#include <stdio.h>

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int i;

    for(i = 0; i < 5; i++) {
        printf("Value of arr[%d] = %d \t Address = arr + %d = %p\n", i, arr[i], i, arr+i);
    }

    return 0;
}

In the code snippet above, arr[i] and *(arr + i) are used interchangeably, emphasising their equivalence and the relationship between arrays and pointers.

Array of Pointers to Character

A practical use case of an array of pointers is to use it as an array of strings. This can be beneficial for memory management. Let's look at an example:

#include <stdio.h>

int main() {
   const char *names[3] = {"Mike", "Tom", "Jerry"};
   
   for (int i = 0; i < 3; i++) {
      printf("names[%d] = %s\n", i, names[i]);
   }
   
   return 0;
}

In this code, we declare an array of three pointers. Each pointer stores the address of a string literal.

Syntax Representing Array in Terms of Pointers in C

Here’s the syntax for representing an array in terms of pointers in C

datatype *arrayName;

Where datatype is the type of data stored at the memory locations pointed by the array pointers.

Example

Here’s an example of the same: 

#include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30};
    int *p = numbers;  // Pointer to the first element of the numbers array
    
    for (int i = 0; i < 3; i++) {
        printf("Value of numbers[%d] = %d\n", i, *(p + i));
    }
    
    return 0;
}

In this example, int *p is a pointer to an integer. It is initialized with the address of the first element of the numbers array using numbers. We can then access the elements of the array using pointer arithmetic and the dereference operator *.

Pointer to Array in C

Pointers can also be used to point to an array. Here, the pointer holds the address of the first element of the array.

datatype (*arrayName)[size];

Pointer to Multidimensional Arrays in C

We can extend this concept to multidimensional arrays. A pointer to 2D array in C is declared as:

datatype (*arrayName)[size1][size2];

Pointer to 3D Arrays in C

Similarly, for a 3D array, the pointer declaration would be:

datatype (*arrayName)[size1][size2][size3];

Array of Pointers in C

This concept is about arrays where each element is a pointer to a certain data type, offering us a different way to manage and manipulate data.

#include <stdio.h>
int main() {
    int number = 50;
    float pi = 3.14;
    char letter = 'a';

    int *pInt = &number;
    float *pFloat = &pi;
    char *pChar = &letter;
    
    void *array[3] = {pInt, pFloat, pChar};
    
    printf("The integer is %d\n", *(int*)array[0]);
    printf("The float is %f\n", *(float*)array[1]);
    printf("The character is %c\n", *(char*)array[2]);
    
    return 0;
}

Conclusion

Mastering the concept of an array of pointer in C is a pivotal step in your journey as a C programmer. While it may seem intimidating at first, with practice, you'll appreciate its benefits, including enhanced memory management and greater data manipulation control.

If you're looking to take your coding skills to the next level, check out the upGrad’s Master of Science in Computer Science course by Liverpool John Moores University, and strengthen your resume to acquire exciting opportunities!

FAQs

1. What is an array of pointers in C? 

An array of pointers in C is a collection of memory addresses. Each address holds the location of different variables or even other pointers. This concept forms a powerful tool to manage and manipulate data efficiently.

2. Can you give an example of an array of pointers in C? 

Here is an example:

#include <stdio.h>

int main() {
   int numbers[] = {10, 20, 30};
   int *p[3];
 
   for(int i = 0; i < 3; i++) {
      p[i] = &numbers[i];
   }
 
   for(int i = 0; i < 3; i++) {
      printf("Value of numbers[%d] = %d\n", i, *p[i]);
   }
 
   return 0;
}

In this example, we create an array of integer pointers p. Each pointer p[i] is assigned the address of the corresponding element in the numbers array.

3. How is a pointer to 2D array in C declared? 

A pointer to 2D array in C is declared as follows: datatype (*arrayName)[size1][size2];. Here, the arrayName is a pointer to a 2D array of size1 by size2.

Leave a Reply

Your email address will not be published. Required fields are marked *