char charArray[10];
char* pArray = charArray;
for(int i = 0; i < 10; i++)
{
*pArray = '\0';
pArray++;
}
From this fragment, what does the *pArray = '\0'; mean? I cannot understand this.
char charArray[10];
char* pArray = charArray;
for(int i = 0; i < 10; i++)
{
*pArray = '\0';
pArray++;
}
From this fragment, what does the *pArray = '\0'; mean? I cannot understand this.
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.
Here's a better alternative to that terrible code, if you want to use strings:
std::string str;
Alternatively, if you really want an array of 10 characters, you can use:
std::array<char, 10> arr;
arr.fill('\0');
If you want a resizable array that will initially contain 10 characters, use:
std::vector<char> vec(10, '\0');
The character literal '\0'
is a NUL character with the value of 0x00. This loop zeros the array.