Public Group

# Pointers

This topic is 4235 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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; } }

##### Share on other sites
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 on other sites
oh thats right forgot we where using 4bytes lol alright ty

I updated it ;)

##### Share on other sites
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

##### Share on other sites
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 on other sites
Yes that helped ty.
Sorry for delay hehe.

1. 1
2. 2
Rutin
22
3. 3
JoeJ
18
4. 4
5. 5

• 15
• 40
• 23
• 13
• 13
• ### Forum Statistics

• Total Topics
631724
• Total Posts
3001903
×