我正在自学 C++,我在 C++ 的指针部分找到了自己。
据我理解,指针将变量的值分配给内存。
但是我遇到了这个问题,答案是588。
我不明白这个数字是怎么来的。
有人可以一步步解释一下588是如何产生的吗?
提前致谢。
#include <iostream>
int main() {
int *p, *q, *t;
// Allocate memory and initialize pointers and values
p = new int;
q = new int;
t = new int;
*p = 17;
*q = 7;
*t = 42;
p = t; // Make pointer p point to the same location as pointer t
t = q; // Make pointer t point to the same location as pointer q
*t = *p * *q;
*q = *q + *t;
std::cout << *t << std::endl;
return 0;
}
如果在每次更改后输出所有三个指针及其值,或者使用调试器,您可以轻松了解正在发生的情况。事情是这样的:
*p = 17;
*q = 7;
*t = 42;
// p points to an int with value 17
// q points to an int with value 7
// t points to an int with value 42
p = t; // Make pointer p point to the same location as pointer t
// p points to an int with value 42 (the same as t)
// q points to an int with value 7
// t points to an int with value 42 (the same as p)
t = q; // Make pointer t point to the same location as pointer q
// p points to an int with value 42 (now different than t)
// q points to an int with value 7 (the same as t)
// t points to an int with value 7 (the same as q)
*t = *p * *q; // *t = (*p) * (*q) = 42 * 7 = 294
// p points to an int with value 42
// q points to an int with value 294 (still the same as t)
// t points to an int with value 294 (still the same as q)
*q = *q + *t; // *q = (*q) + (*t) = 294 + 294 = 588
// p points to an int with value 42
// q points to an int with value 588 (still the same as t)
// t points to an int with value 588 (still the same as q)
std::cout << *t << std::endl; // prints 588 (the same as q)
程序的注释里有写
p = t; // Make pointer p point to the same location as pointer t
t = q; // Make pointer t point to the same location as pointer q
也就是说,在这些语句之后,
*p
等于42
并且*t
等于7
,就像*q
等于7
一样,因为现在两个指针t
和q
指向相同的内存。
因此你有这样的说法
*t = *p * *q;
相当于
*t = 42 * 7;
那就是指针
t
指向的对象,q
弓包含294
。
本声明
*q = *q + *t;
与
相同*t = *q + *t;
因为两个指针都指向同一个对象并且也相同
*t = *t + *t;
或
*q = *q + *q;
所以
294
加上294
会产生588
。