Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Objective-C Basics (Retired) Pointers and Memory Pointer Power

Eduardo Rojas
Eduardo Rojas
4,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?

1 Answer

Thomas Nilsen
Thomas Nilsen
14,957 Points

I'm going to copy something form a good C++ website about incrementing pointers. :

Pointer arithmetic

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;

Outputs:

0012FF7C

0012FF80

0012FF84

0012FF88

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;

Outputs:

0012FF7C

0012FF7E

0012FF80

0012FF82

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.

Eduardo Rojas
Eduardo Rojas
4,084 Points

Thank you it really helped