C Tutorial C Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C - Returning an array from a function



An array of pointers is defined as the same way as an array. The declaration starts with datatype pointed to by the pointer followed by * and name of the array of pointers with size enclosed in square brackets. Please see the syntax below:

Syntax

//integer datatype array of pointer
//with name p and size 5.
int *p[5];

Example:

In the example below, an array called MyArray and array of pointers called p are created. p is assigned the address of MyArray using address-of (&) operator to create array of pointers.

#include <stdio.h>
 
int main (){
  int MyArray[5] = {100, 200, 300, 400, 500};
  int *p[5];

  for(int i = 0; i<5; i++) {
    p[i] = &MyArray[i];
  }

  for(int i = 0; i<5; i++) {
    printf("%i\n", *p[i]);
  }
  return 0;
}

The output of the above code will be:

100
200
300
400
500

Example:

An array of pointers to character can also be used to store a list of strings. Please see the example below:

#include <stdio.h>
 
int main (){
  const char *p[3] = {"Blue", "Red", "Green"};
  
  //see memory location
  for(int i = 0; i<3; i++) {
    printf("%p\n", (p+i));
  }

  //see value stored
  for(int i = 0; i<3; i++) {
    printf("%s\n", *(p+i));
  }
  return 0;
}

The output of the above code will be:

0x7ffda7bdb380
0x7ffda7bdb388
0x7ffda7bdb390
Blue
Red
Green

❮ C - Arrays

5