For loop with pointers and a terminating null

Before the loop pointer pArray points to the first character of array charArray due to its initialization.

char* pArray = charArray;

So inside the loop at the first iteration *pArray yields reference to the first character of the array. Thus the referenced character is assigned by character literal ‘\0’.

*pArray = '\0';

Then the pointer is incermented

pArray++;

and points to the next character. So at the next iteration the second character of the array will be set to ‘\0’.
As the loop has 10 iterations then all 10 characters of the array will be initialized by ‘\0’.

This could be done much simpler in the array definition

char charArray[10] = {};

In this case also all 10 characters of the array will be initialized by ‘\0’.

In C the equivalent construction will look as

char charArray[10] = { '\0' };

Take into account that if the variable pArray is needed only inside the loop to initialize the elements of the array then it is better to write the loop the following way (if you want to use a pointer):

const size_t N = 10;
char charArray[N];

for ( char *pArray = charArray; pArray != charArray + N; ++pArray )
{
  *pArray = '\0';
}

In fact this loop is equivalent to the internal realization of standard algorithm std::fill that you could use.

For example

const size_t N = 10;
char charArray[N];

std::fill( charArray, charArray + N, '\0' );

Or you could use standard functions std::begin and std::end to specify the first and the last iterators fot the array.

Leave a Comment