我刚刚制作了一个关于使用指针传递变量包含在另一个变量中的变量的小愚蠢程序,就像对指针本身的介绍一样。我在分配之前和之后打印了所涉及的所有三个变量的值和位置。但是,作为指针中包含的值,我得到的地址与它指向的变量不同,我不能理解为什么。
这是我的主要计划:
#include <iostream>
#include "01.Point.h"
using namespace std;
int main()
{
int a,b;
cout << "Insert variable's value: ";
cin >> a;
int * point;
cout << "Before assignment:" << endl;
printeverything (a,b,point);
point = &a;
b = * point;
cout << "After assignment:" << endl;
printeverything (a,b,point);
cout << endl;
}
这是我的功能实现:
#include <iostream>
#include "01.Point.h"
using namespace std;
void printeverything (int a, int b, int * c) {
cout << "First variable's value: " << a << "; its address: " << &a << endl;
cout << "Second variable's value: " << b << "; its address: " << &b << endl;
cout << "Pointer's value: " << c << "; its address: " << &c << endl;
}
b成功获得了一个值,所以一切正常,但这是完整的输出:
Before assignment:
First variable's value: 5; its address: 0x7fffee49b77c
Second variable's value: 0; its address: 0x7fffee49b778
Pointer's value: 0x7fffee49b8a0; its address: 0x7fffee49b770
After assignment:
First variable's value: 5; its address: 0x7fffee49b77c
Second variable's value: 5; its address: 0x7fffee49b778
Pointer's value: 0x7fffee49b7ac; its address: 0x7fffee49b770
我的意思是,如果变量x位于第3285位,而我执行p = &x
,则指针p应包含值3285,对吧?那为什么会这样呢?
答案 0 :(得分:6)
在printeverything
函数中,参数/局部变量a
与传递给它的变量完全不同。它碰巧具有相同的名称,但是(就编译器而言)完全是巧合 - 它是具有不同地址的不同变量;你可以通过在函数中为a
赋值,然后在之后打印它来看到这一点 - 你会看到&#34;外部&#34; a
将保持不变。