How to Declare an array of Strings in C

In this article, we are going to learn about how to declare an array of strings in C language. We will learn to do this with the help of multiple techniques.

Different ways to Declare an array of Strings in C


  • Declare Array of Strings in C Using 2D char Array to
  • Declare Array of Strings in C Using char* pointer Array

1. Declare Array of Strings in C Using 2D char Array


In this c program code example, we are going to make use of 2D character array to store strings in a array. The first dimension of this array will tell us how many srings this array can hold.The second dimension of this array will tell us what can be maximum lenghth of the string.We will use the strcpy() function to assign the elements in this array.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(){

    char arr[5][20] = {""};

    strcpy(arr[0], "Sachin");
    strcpy(arr[1], "Dravid");
    strcpy(arr[2], "Sourav");
    strcpy(arr[3], "Sehwag");
    strcpy(arr[4], "Robin");
    	
    printf("The elements of the array are: ");

    for (int i = 0; i < 5; ++i) 
    {
        printf("%s, ", arr[i]);
    }

    return 0;
}

Output

The elements of the array are: Sachin, Dravid, Sourav, Sehwag, Robin, 

2.Declare array in C and initalize element


This is another example of above code where we are assigning the strings to the array elements at the time of initialization itself.This avoids the use of strcpy() function to assign values.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main()
{
    char arr[5][20] = { {"Sachin"},{"Dravid"}, {"Sehwag"},{"Sourav"},{"Robin"} };

    printf("The elements of the array are: ");

    for (int i = 0; i < 5; ++i) 
    {
        printf("%s, ", arr[i]);
    }

    return 0;
}

Output

The elements of the array are: Sachin, Dravid, Sehwag, Sourav, Robin, 

3. Declare Array of Strings in C Using char* pointer Array


#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(){
    char *arr[5] = { "Sachin","Dravid", "Sehwag","Sourav","Robin" };

    printf("The elements in the string array are: ");
    for (int i = 0; i < 5; ++i) 
    {
        printf("%s, ", arr[i]);
    }

    printf("\n");

    return 0;
}

Output

The elements in the string array are: Sachin, Dravid, Sehwag, Sourav, Robin,

4. Declare an array in c and initialize value by index


#include <stdlib.h>
#include <string.h>
#include <stdio.h>


int main(){
    char *arr[5] = {};

    arr[0] = "Sachin";
    arr[1] = "Sachin";
    arr[2] = "Sachin";
    arr[3] = "Sachin";

    printf("The elements in the string array are: ");
    for (int i = 0; i < 5; ++i) 
    {
        printf("%s, ", arr[i]);
    }

    printf("\n");

    return 0;
}

Output

The elements in the string array are: Sachin, Sachin, Sachin, Sachin, (null),