Wednesday, January 29, 2014

Traverse C-String Char By Char

Character pointer points to the address of a single character. By accessing the next address location of the current character pointer, until it points to the '\0' char, it gives you the availability to read a whole c-string in a while loop.
Following sample project created by qt creator and contains following files:

1-TraverseC-StringCharByChar.pro
2-main.cpp



TraverseC-StringCharByChar.pro file contains project configuration.
TARGET = TraverseC-StringCharByChar
SOURCES += main.cpp

main.cpp file contains just main method which is showing how to traverse a c-string till an end-of-string character is found.

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
   char* str = "C-StringToTraverse";
   cout<<"Input String = "<<str<<endl<<endl;
   while(*str)
   {
        cout << *str<<endl;
        ++str;
   }
   return 0;
}

A char* points to the start address of the c-string. By incrementing 1, the address of the char* shows the address of the next character in the c-string. While loop executes until it finds the '\0' character which is corresponding to the 0. Therefore, the while loop terminates, because the current char pointer points to 0 which equals to false.
Console output is as follows :