I am just wondering what the difference is between using '*(pntr + 1)' or '*pntr[1]'. When using '*pntr[1]', to point to an array of my variable 'char loc', I get just the character that I pointed to. But when using '*(pntr + 1)', I get the character that I pointed to, and any other characters that followed after it in that string.
In my code, I placed comments at the bottom that explains my guess of what is going on.
Code:// Having fun with pointers. #include <iostream> using namespace std; int main() { char loc[80]; // Define variable array. char *pntr[4] = {&loc[4], &loc[9], &loc[14], &loc[19]}; // Define pointer array to index locations 4, 9, 14, and 19 of variable loc. cin >> loc; // Input string to loc cout << *pntr[1] << "\n"; // output one of the characters of loc that were assigned to the pointer (*pntr). (the character in loc[9] is displayed.) system( "PAUSE" ); return 0; } /************************************************************************************************************************ In the case cin >> loc; cout << *pntr[1]; only the specified character is displayed. But if cin >> loc; cout << *(pntr + 1); Or cin >> loc; cout << *pntr; (is the same as 'cout << *(pntr + 0)') the specified character is displayed, but every character after it is also displayed. The reason for this behavior I will explain. Remember that the pointer is indexing within its own array first, instead of pointing directly to a 'loc' array location. So when outputing '*pntr;' or '*(pntr + 0)', I think that the problem is caused from double indirect addressing. '*(pntr + 1);' differs from '*pntr[1]' as '*(pntr + 1) is an indirect address to *pntr[1], (I think). *************************************************************************************************************************/
I hope I made sense.



LinkBack URL
About LinkBacks
. 



