在分配指针后,你能为指针指向的东西分配一个变量名吗?
Can you assign a variable name to the thing a pointer is pointing at, after the pointer has been allocated?
假设我有一些代码,其中有一个变量 a,我分配了一个指向 a
:
的指针
int a = 5;
int* ptr = &a;
但是,在此之后,我想给出变量a
占用名称b
的内存位置。
int b = a; // doesn't work, because it only copies the value
&b = ptr; // doesn't work, not an assignable value
ptr = &b; // doesn't work, this moves the pointer to point to b
// instead of renaming the location that ptr already pointed to
这可能吗? (这样做没有充分的理由 - 只是好奇。)
--
编辑:这个问题不是关于指针和引用之间的区别,而是关于如何通过使用它们来实现目标,因此不是 "what is the difference between references and pointers?"
的重复
不,分配(或重命名)变量名(标识符)是不可能的。
不过,如果您有兴趣,可以随时
int * b;
b = &a;
其中 b
指向 变量 a
。对 *b
所做的更改将 反映 到 a
,反之亦然。
您可以有多个指针指向同一个地方:
int i = 10;
int* p1 = &i;
int* p2 = &i;
int* p3 = p2;
正如你已经发现的,你不能说 &b = ptr;
I want to give the memory location that variable "a" occupies the name "b"
你要的是参考,如果我理解正确的话。
int& b = a; // b is an alias of a
assert(&a == &b); // the same memory location
b = 6; // the value of both a and b changed to 6
int& b = a
将整数引用 a
绑定到 b
。变量a
的地址完全未修改。
它只是意味着 a 的所有使用(引用)实际上使用分配给 b
.
的值
假设我有一些代码,其中有一个变量 a,我分配了一个指向 a
:
int a = 5;
int* ptr = &a;
但是,在此之后,我想给出变量a
占用名称b
的内存位置。
int b = a; // doesn't work, because it only copies the value
&b = ptr; // doesn't work, not an assignable value
ptr = &b; // doesn't work, this moves the pointer to point to b
// instead of renaming the location that ptr already pointed to
这可能吗? (这样做没有充分的理由 - 只是好奇。)
-- 编辑:这个问题不是关于指针和引用之间的区别,而是关于如何通过使用它们来实现目标,因此不是 "what is the difference between references and pointers?"
的重复不,分配(或重命名)变量名(标识符)是不可能的。
不过,如果您有兴趣,可以随时
int * b;
b = &a;
其中 b
指向 变量 a
。对 *b
所做的更改将 反映 到 a
,反之亦然。
您可以有多个指针指向同一个地方:
int i = 10;
int* p1 = &i;
int* p2 = &i;
int* p3 = p2;
正如你已经发现的,你不能说 &b = ptr;
I want to give the memory location that variable "a" occupies the name "b"
你要的是参考,如果我理解正确的话。
int& b = a; // b is an alias of a
assert(&a == &b); // the same memory location
b = 6; // the value of both a and b changed to 6
int& b = a
将整数引用 a
绑定到 b
。变量a
的地址完全未修改。
它只是意味着 a 的所有使用(引用)实际上使用分配给 b
.