C Programming Arrays Of Pointers

Last modified by Microchip on 2023/11/09 09:06

Declaration

An array of pointers is an ordinary array variable whose elements happen to be all pointers.

1 char *p[4];

This creates an array of four pointers to char. The array p[] itself is like any other array. The elements of p[], such as p[1], are pointers to char.

Back to Top

Initialization

Initializing an element of an array of pointers is just like initializing ordinary pointers, but we must include the array index. This example assigns the address of to the pointer in the element of the array.

1 p[0] = &x;

 This next example assigns the address of the first character in the string to the pointer in element 0 of the array.

1 p[0] = "My string";

 This example shows how you would populate the array of pointers in the following picture.

Graphic showing how you would populate the array of pointers

1 p[0] = "On";
2 p[1] = "Off";
3 p[2] = "Main";
4 p[3] = "Aux";

This would create the strings in memory and initialize each of the pointers in the array to point to a particular string.

Back to Top

Dereferencing

To use the value pointed to by a pointer array element, just dereference it like you would an ordinary variable:

1 y = *p[0];

Using *p[0] is the same as using the object it points to, such as x or the string literal "My String" from before.

Back to Top

Accessing Strings

Example

1 int i = 0;
2 char *str[] = {"Zero", "One", "Two", "Three", "Four", "\0"};
3
4 int main(void)
5 {
6     while(*str[i] != '\0')
7         printf("s\n", str[i++]);
8     while(1);
9 }

Back to Top