Array of Pointers

Array of Pointers in C

An array of pointers is simply an array that stores addresses, rather than actual values.

Declaration

Like a regular array, an array of pointers can be declared easily:

int *p[10]; // Creates an array of 10 pointers, each pointing to an integer

Assigning Addresses

We can make the pointers point to integer variables:

int a = 10, b = 20, c = 30; p[0] = &a; p[1] = &b; p[2] = &c;

Here, p[0], p[1], and p[2] point to the variables a, b, and c respectively.


Advantages

  1. An array of pointers can point to an array of data items.

  2. Pointers can be reordered without moving the actual data items.

  3. Reordering pointers is much faster than reordering large data items such as records or strings.

  4. For example, sorting an array of strings is easier by reordering pointers rather than swapping the strings themselves.


Example: Sorting Names Using Array of Pointers

#include <stdio.h> #include <string.h> void main() { char name[100][50]; // Array to store names char *ptr[100]; // Array of pointers char *temp; // Temporary pointer for swapping int i, j, n; printf("Enter number of names: "); scanf("%d", &n); fflush(stdin); printf("Enter names:\n"); for(i = 0; i < n; i++) { gets(name[i]); // Read name ptr[i] = name[i]; // Make pointer point to name[i] } // Sorting using pointers for(i = 0; i < n - 1; i++) { for(j = i + 1; j < n; j++) { if(strcmp(ptr[i], ptr[j]) > 0) { temp = ptr[i]; ptr[i] = ptr[j]; ptr[j] = temp; } } } printf("Names in sorted order:\n"); for(i = 0; i < n; i++) { printf("%s\n", ptr[i]); } }

How It Works

  • name[100][50] stores the actual strings.

  • ptr[100] stores pointers to the strings.

  • Sorting is done by swapping pointers, not the strings themselves.

  • This approach is memory-efficient and faster for large data.

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays