I was just experimenting with the use of pointers when dealing with arrays and I’ve become a bit confused with how C++ is handling the arrays. Here are the relevant bits of code I wrote:
//declare a string (as a pointer)
char* szString = "Randy";
cout << "Display string using a pointer: ";
char* pszString = szString;
while (*pszString)
cout << *pszString++;
First off, when I tried using cout to write what was in “pszString” (without de-referencing)I was a bit surprised to see it gave me the string. I just assumed it was because I gave the pointer a string and not a variable.
What really caught my attention though is that when I removed the asterisk from the line cout << *pszString++; it printed “Randyandyndydyy”. I’m not sure why it’s writes the array AND then writes it again with 1 letter less. My reasoning is that after writing the char string the increment operator immediately brings the index to the next letter before it can reach the null terminator. I don’t see why the null terminator wouldn’t cause the loop to return false after the string is output for the first time otherwise. Is this the right reasoning? Could someone explain if I’m getting this relationship between arrays and pointers?
couthas anoperator<<overload forchar*to print the entire string (that is, print each character until it encounters a0). By contrast, thecharoverload forcout‘soperator<<prints just that one character. That’s essentially the difference here. If you need more explanation, read on.When you dereference the pointer after incrementing it, you’re sending
coutachar, not andchar*, so it prints one character.So
cout << *pszString++;is like doingWhen you don’t dereference the pointer, you’re sending it a
char*socoutprints the entire string, and you’re moving the start of the string up by one character in each iteration through the loop.So
cout << pszString++;is like doingIllustration with a little loop unrolling:
For
cout << *pszString++;For
cout << pszString++;I am glad you are experimenting with pointers this way, it’ll make you actually know what’s going on unlike many programmers who will do anything to get away from having to deal with pointers.