CodeBlanks Logo Icon CodeBlanks

Array of pointers

  • C course
  • Intermediate
  • Lesson 2/116
  • 5 min

Learn to create and use an array of pointers.

Array of pointers

An array of pointers is an array whose elements are pointers. In C the syntax int *arr[3]; declares an array of three int * elements.

Example: int a = 1, b = 2, c = 3; int *arr[3] = {&a, &b, &c};. Here arr[0] equals &a and arr[1] equals &b. *arr[1] gives you the value of b. Pointer arrays are common, especially for string lists like argv.

Pointer arrays for string lists

The most common use of pointer arrays is for string lists. In C a string is a char *; so a list of strings is held as an array of char *.

Example: char *names[3] = {"Ayşe", "Mehmet", "Zeynep"};. Each string literal lives in read-only memory; the array holds only pointers to them. names[0] gives the first string; names[1][0] gives the first letter of the second string. This structure is used everywhere from command line arguments to menu systems.

Practice Print a list of names

Declare a char *names[3] array with three names (e.g. "Ayşe", "Mehmet", "Zeynep"). Use a for loop to print each name on its own line with printf.

Starter code

main.c
#include <stdio.h>

// Declare the names array
// Loop and print each name

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    char *names[3] = {"Ayşe", "Mehmet", "Zeynep"};
    for (int i = 0; i < 3; i++) {
        printf("%s\n", names[i]);
    }
    return 0;
}

Expected output

Ayşe
Mehmet
Zeynep

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the array of pointers parts

Term Meaning
int *arr[3] Array declaration
arr[0] First pointer
*arr[1] Pointed value
arr[i] = &x Assignment

2 How do you declare an array of three strings?

  • char **names[3];
  • char names[3];
  • char *names[3]; Correct answer
  • char *(names);

Explanation: Char *names[3]; — three char pointers.

3 Print the second string of the array

Question
char *names[3] = {"Ayşe", "Mehmet", "Zeynep"};
printf("%s\n", names[____]);
Answer
char *names[3] = {"Ayşe", "Mehmet", "Zeynep"};
printf("%s\n", names[1]);

Explanation: names[1] points to the second string "Mehmet".

All lessons in Intermediate