Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Eduardo Rojas4,084 Points
when you auto increment the pointer arent you incrementing the value of the "location" of this value? (0x9FFF0)
my point is when you auto increment in the example that the video gave is int like resulting to 0x10FFF0 or something like that?
Thomas Nilsen14,957 Points
I'm going to copy something form a good C++ website about incrementing pointers. :
The C language allows you to perform integer addition or subtraction operations on pointers. If pnPtr points to an integer, pnPtr + 1 is the address of the next integer in memory after pnPtr. pnPtr - 1 is the address of the previous integer before pnPtr.
Note that pnPtr+1 does not return the address after pnPtr, but the next object of the type that pnPtr points to. If pnPtr points to an integer (assuming 4 bytes), pnPtr+3 means 3 integers after pnPtr, which is 12 addresses after pnPtr. If pnPtr points to a char, which is always 1 byte, pnPtr+3 means 3 chars after pnPtr, which is 3 addresses after pnPtr.
When calculating the result of a pointer arithmetic expression, the compiler always multiplies the integer operand by the size of the object being pointed to. This is called scaling.
The following program:
int nValue = 7; int *pnPtr = &nValue; cout << pnPtr << endl; cout << pnPtr+1 << endl; cout << pnPtr+2 << endl; cout << pnPtr+3 << endl;
As you can see, each of these addresses differs by 4 (7C + 4 = 80 in hexadecimal). This is because an integer is 4 bytes on the author’s machine.
The same program using short instead of int:
short nValue = 7; short *pnPtr = &nValue; cout << pnPtr << endl; cout << pnPtr+1 << endl; cout << pnPtr+2 << endl; cout << pnPtr+3 << endl;
Because a short is 2 bytes, each address differs by 2.
It is rare to see the + and – operator used in such a manner with pointers. However, it is more common to see the ++ or — operator being used to increment or decrement a pointer to point to the next or previous element in an array.