简体   繁体   English

c++ 中 arrays 指针的奇怪行为

[英]Strange Behavior with pointers with arrays in c++

Hello people of Stacked Overflow.你好 Stack 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.最近我在大学计算机科学class学习指针和arrays,为了测试我对两者的理解深度,我试着想出一些令人困惑的实例,看看我是否可以正确预测结果的结果。 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;我困惑的主要部分解决了一部分,所以我在代码上注释掉了一行,我想知道为什么像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.在 C++ 中, ++运算符递增其操作数。 The expression表达方式

++valptr

by itself is logically equivalent to valptr=valptr+1 , but it occurs as part of the expression. by itself 在逻辑上等同于valptr=valptr+1 ,但它作为表达式的一部分出现。 valptr gets increment to a new value as part of the expression that it occurs in. That's what ++ does. valptr作为它出现的表达式的一部分而增加到一个新值。这就是++所做的。 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.++--在其操作数之前或之后出现时的工作方式不同,但这有点偏离主题,您可以在 C++ 教科书的帮助下自行研究。

And this is exactly where you are "assigning anything further".而这正是您“进一步分配任何东西”的地方。 So, *valptr before, and after this line, produces a different result.因此,此行之前和之后的*valptr会产生不同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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