简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM