Array of Strings in C

In this blog post, I will try to teach what is an array of strings in C with the help of example code. Also, I will also explain some invalid operations that you should avoid before using an array of strings.

 

What is an Array of Strings in C?

As you know an array is essentially a collection of elements. And the data types for all elements must be the same and stored at the contiguous memory location. Similarly, an array of strings means a collection of several strings.

The string is a 1D array of characters terminated with the null character. Since strings are arrays of characters, the array of strings will evolve into a two-dimensional array of characters. You can create an array of strings using the array of pointers to the string.

If you are not able to understand don’t worry I will explain with an example, then I believe you are able to understand.

Syntax of the array of strings in C:

 

1. Using the 2D array:

Let’s see the first syntax of the array of strings using the 2D array.

char arrayName [maxNumberOfStrings][maxLenOfString];

Here,

arrayName:- It is the name of the 2D array.

maxNumberOfStrings:- It is the max number of strings that you want to store in your string array.

maxLenOfString:- It is the maximum length of the string( max number of characters in the string).

 

Consider the below example,

char listOfName[5][10] = {"PoojaS1", "PoojaS2", "PoojaS3", "PoojaS4", "PoojaS5"};

In the above example, listOfName is the name of a 2d array. This array could store a maximum of 5 strings and the max length of strings would be 10.

In the above example, I have initialized my 2d array with some names that as “PoojaS1”, “PoojaS2”,.. etc. Because a 2d array of characters is basically an array of an “array of characters”, so if you want you can also initialize the array of strings using the below-mentioned approach.

char listOfName[5][10] =
{
    {'P','o','o','j','a','S1','\0'},
    {'P','o','o','j','a','S2','\0'},
    {'P','o','o','j','a','S3','\0'},
    {'P','o','o','j','a','S4','\0'},
    {'P','o','o','j','a','S5','\0'}
};

 

The below is a representation of the above-mentioned 2d array, it helps you to understand it memory layout (assuming the char size is 1 byte).

Array of strings in c

 

Example of Array of String in C (2D array):

 

1. Reading and Displaying Array of Strings using single for loop:

Consider the below example  C code,

/*
C Program to print Array
of strings
*/
#include <stdio.h>

#define MAX_NUMBER_STRINGS 5
#define MAX_LEN_STRING 10

int main()
{
    int stringIndex = 0;
    char listOfName[MAX_NUMBER_STRINGS][MAX_LEN_STRING] =
    {"PoojaS1", "PoojaS2", "PoojaS3", "PoojaS4", "PoojaS5"};

    for (stringIndex= 0; stringIndex < MAX_NUMBER_STRINGS; ++stringIndex)
    {
        printf("%s\n", listOfName[stringIndex]);
    }

    return 0;
}

Output:

PoojaS1
PoojaS2
PoojaS3
PoojaS4
PoojaS5

 

Explanation:

In the above example, I have created an array of strings and initialized it with some names at the time of declaration.

char listOfName[MAX_NUMBER_STRINGS][MAX_LEN_STRING] =
{"PoojaS1", "PoojaS2", "PoojaS3", "PoojaS4", "PoojaS5"};

In the next statement, I am reading strings of the array using the “for loop”.

for (stringIndex= 0; stringIndex < MAX_NUMBER_STRINGS; ++stringIndex)
{
    printf("%s\n", listOfName[stringIndex]);
}

 

2. Reading and Displaying Array of Strings using nested for loop:

Consider the below example,

/*
C Program to print Array
of strings
*/
#include <stdio.h>
#include <string.h>

#define MAX_NUMBER_STRINGS 5
#define MAX_LEN_STRING 10

int main()
{
    int stringIndex = 0;
    int charIndex = 0;
    char listOfName[MAX_NUMBER_STRINGS][MAX_LEN_STRING] =
    {"PoojaS1", "PoojaS2", "PoojaS3", "PoojaS4", "PoojaS5"};

    for (stringIndex= 0; stringIndex < MAX_NUMBER_STRINGS; ++stringIndex)
    {
        const int stringLen = strlen(listOfName[stringIndex]);
        for (charIndex= 0; charIndex < stringLen; ++charIndex)
        {
            printf("%c", listOfName[stringIndex][charIndex]);
        }
        //print new line
        printf("\n");
    }

    return 0;
}

Output:

PoojaS1
PoojaS2
PoojaS3
PoojaS4
PoojaS5

 

2. Array of String in C (array pointer to string):

Right now you have learned how to create an array of strings using the 2D array. Now you are going to learn how you can create an array of strings using the 1D array.

This array will be the array of character pointers. In this each pointer point to a string. You should remember that if it points to a literal string, then you can not modify its value. You can read this article, “C String Literals with Its Types“.

Syntax:

char *arrayName [maxNumberOfStrings];

Consider the below example,

char * str[5] = {"PoojaS1", "PoojaS2", "PoojaS3", "PoojaS4", "PoojaS5"};

In the above example, str is the name of a 1d array. This size of the array is 5 which means it could point to a maximum of 5 strings.

Below is a memory representation of the above-mentioned array of strings.

array of string using 1D array

 

/*
C Program to print Array
of strings
*/
#include <stdio.h>

//max number of string
#define MAX_NUMBER_STRINGS 5


int main()
{
    int stringIndex = 0;

    char * str[MAX_NUMBER_STRINGS] =
    {"PoojaS1", "PoojaS2", "PoojaS3", "PoojaS4", "PoojaS5"};

    for (stringIndex= 0; stringIndex < MAX_NUMBER_STRINGS; ++stringIndex)
    {
        printf("%s\n", str[stringIndex]);
    }
    return 0;
}

Output:

PoojaS1
PoojaS2
PoojaS3
PoojaS4
PoojaS5

 

Some Invalid Operation on an Array of String:

Here I have list-down some invalid operations on an array of strings.

1. Don’t try to modify the literal strings:

As you know string literals are not modifiable. So if a program attempts to modify the static array formed by a string literal, the behavior is undefined.

/*
C Program to print Array
of strings
*/
#include <stdio.h>


#define MAX_NUMBER_STRINGS 3


int main()
{
    char * str[MAX_NUMBER_STRINGS] =
    {"Aticleworld1", "Aticleworld2", "Aticleworld3"};

    /*
      Here I want to change, Aticleworld1 to aticleworld1
      This operation is illegal because try to modify literal
      string.
    */
    str[0][0]= 'a';

    printf("%s\n",str[0]);


    return 0;
}

Output: UB

 

But don’t be confused that you can not change the pointer value in the above example, you can change it. The only restriction for literal strings. consider the below example.

/*
C Program to print Array
of strings
*/
#include <stdio.h>


#define MAX_NUMBER_STRINGS 3


int main()
{
    char * str[MAX_NUMBER_STRINGS] =
    {"Aticleworld1", "Aticleworld2", "Aticleworld3"};

    /*
      Here I want to replace, Aticleworld1 to aticleworld1
      This operation is valid operation array
      is collection pointer to char.
    */
    str[0] = "aticleworld1";

    printf("%s\n",str[0]);


    return 0;
}

Output: aticleworld1

 

2. Don’t apply the standard string functions that try to modify the literal strings:

Consider the below example, in which strcpy function is used.

/*
C Program to print Array
of strings
*/
#include <stdio.h>
#include <string.h>


#define MAX_NUMBER_STRINGS 3


int main()
{
    char * str[MAX_NUMBER_STRINGS] =
    {"Aticleworld1", "Aticleworld2", "Aticleworld3"};


    strcpy(str[0], "abc");

    printf("%s\n",str[0]);


    return 0;
}

Output: UB

 

Some other C string library functions show also undefined behavior.

Operation 1: strcat(arr[0], "Aticleworld"); // invalid

Operation 2: gets(arr[0]);           // invalid


Operation 3: fgets(arr[0],10,stdin)  //invalid


Operation 4: scanf("%s", arr[0]);    // invalid

 

3. Don’t access beyond the allowed memory:

If you try to access the array string beyond the allocated memory the behavior of the code is undefined.

/*
C Program to print Array
of strings
*/
#include <stdio.h>
#include <string.h>


#define MAX_NUMBER_STRINGS 3


int main()
{
    char * str[MAX_NUMBER_STRINGS] =
    {"abc", "cde", "efg"};

    //try to access first string
    //character beyond its memory
    printf("%c\n",str[2][12]);

    return 0;
}

Output: Undefined Behaviour

 

Recommended Post