I am trying to grasp pointers and I have this simple code for which I need some explanation.
I need to copy one char array to another. In my main function I have this code:
const int MAX_SIZE = 100;
char x[MAX_SIZE] = "1234565";
char* y = new char[MAX_SIZE];
copyArray(x, y);
std::cout << y;
delete [] y;
Now comes the question, how does this code (which works jut fine):
while ((*dest = *source) != '\0')
{
dest += 1;
source += 1;
}
Differ from this (gives strange characters at the end):
while (*source != '\0')
{
*dest = *source;
dest += 1;
source += 1;
}
Looking at this it seems those two functions are pretty similar. It makes sense that we are copying until we reach a null-terminator in the source string, right (2nd function)?
But it's not working correctly - I get some strange characters at the end of the copied array. However, the first function works just fine.
void copyArray(const char* source, char* dest);
while ((*dest = *source) != '\0')guarantees that the necessary terminating'\0'character will be copied before the loop ends. Also see idownvotedbecau.se/nodebuggingwhile (*source != '\0')loop does not "won't terminate the string". It won't terminate the character array. A character array is not a string until it has a null character.