Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strange Behavior with pointers with arrays in c++

Hello people of Stacked Overflow! Recently I’ve been learning about pointers and arrays in my college Computer Science class. In order to try to test the depth of my understanding of the two, I tried to come up with some confusing instances in order to see if I could correctly predict the outcome of the result, as well as the reason for why the result is what it is… Well I seem to have confused myself too much, because I don’t understand these few instances that I have come up with.

int vals[] = {1,2,3,4,5,6};
int* valptr = vals;

cout<<*valptr<<endl;
cout<<(**&vals)+1<<endl;
//cout<<*(++valptr)<<endl;
// cout<<*(++vals)<<end1;
cout<<*&valptr[0]<<endl;
cout<<**(&valptr)<<endl;
cout<<valptr[0]<<endl;

Part of the main part of my confusion was solved, so I commented out a line on the code, I wanted to know why lines such as cout<<**(&valptr)<<endl; actually run, I’m just confused on why that works. why does it only work when I have the & on it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’m very confusing seeing as in nowhere in that short code am I
assigning anything further.

Not quite, you are, indeed, assigning a new value "further". You are doing it right here:

cout<<*(++valptr)<<endl;

In C++, the ++ operator increments its operand. The expression

++valptr

by itself is logically equivalent to valptr=valptr+1, but it occurs as part of the expression. valptr gets increment to a new value as part of the expression that it occurs in. That’s what ++ does. You can also make a pretty good guess what the -- operator does, too. And ++ and -- works differently when it occurs before or after its operand, but that’s slightly off-topic and is something you can investigate on your own, with your C++ textbook’s help.

And this is exactly where you are "assigning anything further". So, *valptr before, and after this line, produces a different result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading