Skip to study material
← Question index

QUESTION 16 · Pointers and Arrays

Explain an array of pointers with a string example.

5 marks

Answer in brief

An array of pointers stores several pointer values. Each element can identify a different object or string.

Declaration

const char *names[3] = {"C", "Python", "Java"};

Meaning

names[0] points to the first character of "C", names[1] to "Python" and names[2] to "Java". Each names[i] is a pointer, not an entire fixed-width row of characters. The string literals exist separately and must not be modified.

Access and output

puts(names[i]) displays the selected null-terminated string and adds a newline. names[i][j] can read the j-th character when that index is valid for the selected string. The null terminator belongs to each separate string; it does not terminate the array of pointers itself.

Comparison with a character matrix

char names[3][10] reserves three rows of ten characters, including room for each terminator. const char *names[3] reserves three pointers that identify existing strings of potentially different lengths. The layouts and parameter types differ. An array of pointers is not automatically one contiguous character matrix.

Uses and complexity

Pointer arrays are useful for menus, labels or lists of independently stored strings. Selecting names[i] takes O(1) work. Displaying all characters takes time proportional to the total displayed string length, plus the list traversal. The pointer array needs storage for three pointers in this fixed example; the strings have their own storage.

Important point

The const applies to the characters reached through each pointer. It does not by itself make each pointer element impossible to reassign to another suitable string.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>

int main(void)
{
    const char *names[3] = {"C", "Python", "Java"};
    for (int i = 0; i < 3; ++i) { puts(names[i]); }
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

C
Python
Java

Related exam questions

Related questions in the array of pointers category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q1(d) · 3 marks

    What do you mean by an array of pointers?

    Paper P02 · page 1

View this category in the exam question bank →