Array of pointers in C example program

Last Updated On Sunday 3rd Oct 2021

Array of Pointers in C

  • Since a pointer type is just another type, we can have arrays of pointers.

C Declare Array of Pointers

  • To declare an array of pointers, we use the following syntax.
	some_type* pointer_name[number_of_elements];
	
  • To declare an array of pointers to char.
	#include <stdio.h>

int main(void) {
  char * langs[] = {
    "Java",
    "Python",
    "JavaScript",
    "Ruby"
  };
  for (int i = 0; i < 4; i++) {
    printf("%s\n", langs[i]);
  }
}
	

Output

	Java
Python
JavaScript
Ruby
	
	  char * langs[] = {
    "Java",
    "Python",
    "JavaScript",
    "Ruby"
  };
	
  • The Above declares an array of pointers of type char* and initializes them with string constants
  • We then use the for loop to print out all three sentences by accessing an appropriate pointer through a subscript operator as in langs[i]
  • The subscript operator [] acts as a dereference operator.
  • langs[i] expression is equivalent to *(langs+i).
  • Using a subscript operator with an index on a pointer as in langs[i] means increment a pointer by i places and dereference it.