我的代码使用C ++
#include <iostream>
using namespace std;
int main() {
int i = 10, j = 20, k;
int* p = &i;
int* q = &j;
*p += 1;
p = &k;
*p = *q;
p = q;
*p = i;
cout << j << endl;
return 0;
}
请为我解释为什么j
= 11?我倾向于这是一个不同的值,但它是11。
答案 0 :(得分:1)
希望您能理解这一点,您需要知道,当指针指向内存时,我们将* pointer = valueX =>内存设置为valueX。
#include <iostream>
using namespace std;
int main() {
int i = 10, j = 20, k;
int* p = &i; // p point to i =>*p=10
int* q = &j; // q point to j =>*q=20
*p += 1; // *p = *p + 1 => *p=11 => i = 11
p = &k; // p point to k
*p = *q; // *p = 20 => k = 20
p = q; // p point to j (q point to j)
*p = i; // set value of memory which p point to to value of i => *p = 11 => j = 11
cout << j << endl;
return 0;
}