Sign in to follow this  
DeathLetum

Pointers

Recommended Posts

DeathLetum    127
Alright been messing around wiht pointers tutorials and all and got stuck on some code. Now the thing i cant seem to understand is at a certain point says that ptr += 2; mean it take ptr and adds 8 to it?? that totaly lost me. #include <iostream> using namespace std; main() { int *ptr; ptr = new int[5]; *ptr = 5; // this is ptr[0] = 5 ptr[1] = 10; // ptr[1] = 10 ptr += 2; // the tutorial says its ptr +8 but i cant seem to figure out why. *ptr = 15; // now this one and next one really got me lost.? ptr -= 2; for (int i = 0; i < 5; i++) { cout << ptr[i] << endl; } }

Share this post


Link to post
Share on other sites
dave    2187
If you have an array of chars and have a pChar pointing to an element then pChar+2 gives you the character two ahead of the one you're on. In terms of memory this is 2 bytes since a char is a byte. If however you have an array of ints and a pInt, each int is 4 bytes typically and so when you do pInt+2 you are moving two ints along the array but 8 bytes.

*ptr = 5; // this is ptr[0] = 5
This sets the first integer in the array to the value 5.

ptr[1] = 10; // ptr[1] = 10
This sets the second integer in the array to the value 10.

ptr += 2;
This makes ptr point at the 3rd integer in the array.

*ptr = 15;
This sets the 3rd integer in the array to the value 15.

ptr -= 2;
This moves the pointer back two integers and is now pointing at the first integer in the array.

Hope that helps,

Dave

Share this post


Link to post
Share on other sites
dave    2187
With:

ptr -= 2;

The pointer holds an address to somewhere in memory where that array of integers is stored. In memory the integers are arranged in sequence, a contiguous block. Each integer is 4 bytes and so you have:

[4bytes][4bytes][4bytes][4bytes][4bytes]
^ ^
| |
ptr ptr
-2 ints
-8 bytes


If the pointer is pointing at the 3rd integer and you move it back 2 integers, you are moving the pointer backwards in the memory by 8 bytes, as you can see in the diagram. So when you -= 2, 2 * the size of the item stored (which is 4) is subtracted from the address of the pointer.

Does that help,

Dave

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this