Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of ++ operator in a pointer

Tags:

c++

pointers

I have an array of structs, and I made a pointer to the first element in the struct. I have seen the ++ operator being used in my code on the pointer, like this: ptrStruct++, what does this exactly do? Go to the next array position? Or it is used as an operator overloading?

Code here, and the objects are from Ogre3D:

RGBA colours[nVertices];
RGBA *pColour = colours;
rs->convertColourValue(ColourValue(1.0,0.0,0.0), pColour++); //0 colour
rs->convertColourValue(ColourValue(1.0,1.0,0.0), pColour++); //1 colour
rs->convertColourValue(ColourValue(0.0,1.0,0.0), pColour++); //2 colour
like image 707
Pacha Avatar asked Dec 17 '25 19:12

Pacha


1 Answers

++, when applied to a pointer, advances said pointer to the next item. It does this by scaling based on the size of the item being pointed to.

So, if you have a char *pc pointing at location 0x1000, pc++ will advance it to the next char, or 0x1001. However, an int *pi (assuming sizeof (int) is 4) would advance from location 0x1000 to 0x1004.

This is not something you normally need to worry about unless you're casting between different pointers. Suffice to say that:

RGBA colours[nVertices];
RGBA *pColour = colours;    // same as &(colours[0])
pColour++;                  //     now &(colours[1])

will simply advance pColour to point to colours[1].

like image 180
paxdiablo Avatar answered Dec 20 '25 10:12

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!