Pointers

Started by
5 comments, last by DeathLetum 17 years, 4 months ago
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 << endl; } }
Advertisement
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
oh thats right forgot we where using 4bytes lol alright ty
I updated it ;)
tyvm bro that helps a alot its all clear accept the ptr -= 2;
i know it send me back to ptr[0] but dont know why i would do that hehe
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
Yes that helped ty.
Sorry for delay hehe.

This topic is closed to new replies.

Advertisement