Monday, February 3, 2014

Traverse Array Of C-Strings Char By Char (char* array[])

char* arrayOfCStrings[] is used as an array of pointer to character. Because it is an array and each index of the array contains a pointer to the starting character of a c-string which is terminated by an end-of-string ‘\0’ character.

Following sample project created by qt creator and contains following files:
1- TraverseArrayOfCStringsCharByChar.pro
2- main.cpp
           

TraverseArrayOfCStringsCharByChar.pro file contains project configuration.

TARGET = TraverseArrayOfCStringsCharByChar
SOURCES += main.cpp

main.cpp file contains main method which is showing how to traverse an array of c-strings till an end-of-string character is found for each string.

#include <stdio.h>

int main(int argc, char *argv[])
{

    char* arrayOfCStrings[] = {"string1","string2","string3"};

    int stringCount = sizeof(arrayOfCStrings)/sizeof(char*);

    printf("Total number of strings in the string array : %d \n",stringCount);

    int i = 0;
    while(i<stringCount)
    {
        const char* currentString = arrayOfCStrings[i];
        while((*currentString))
        {
            printf(" %c ", *currentString);
            currentString++;
        }
        printf("\n");
        ++i;
    }

    return 0;
}
arrayOfStrings is initialized by curly braces.

char* arrayOfCStrings[] = {“string1”, “string2”, “string3”};

Total number of strings in the array is computed by dividing the total size of the arrayOfStrings to the size of each char* element.
int stringCount = sizeof(arrayOfCStrings)/sizeof(char*);

Outer while loop iterates till it reaches the total number c-strings. And the inner while loop iterates for each character in the current c-string till the end-of-string '\0' character is found. Console output displays the total number of c-strings in the array and each character of the current c-string in a new line.

No comments:

Post a Comment