【问题标题】:Difference between & and * [duplicate]& 和 * 之间的区别 [重复]
【发布时间】:2020-05-27 11:49:24
【问题描述】:

这两个运算符有什么区别? 我的理解是它们都指向它们所使用的变量的内存位置。

例如

int p;
foo(*p,&p);

【问题讨论】:

  • 表达式&p返回变量p的位置(地址)。表达式*p 返回位于p 变量内的值,通常称为取消引用。因此,如果p 包含值2020,那么*p 将返回存储在位置2020 的整数(如果可能)。
  • @ThomasMatthews 在问题的代码中,*p 不会编译。一元 * 的操作数必须是指针类型的表达式。指针不能包含值2020(类型为int),尽管它可能包含值(int*)2020
  • @KeithThompson "一元 * 的操作数必须是指针类型的表达式" - 或实现成员 operator* 的类/结构类型的实例.

标签: c++ pointers


【解决方案1】:

&p获取指向整数p的指针->即存储p的内存地址。

*p“取消引用”指针,即查看p提供的内存地址处的对象并返回该对象。

您上面的代码是无效的 C,因为您不能取消引用 int

error: indirection requires pointer operand ('int' invalid)

请考虑以下内容:

// Create an integer
int p = 1234;
printf("Integer: %d\n", p);

// Get the pointer to that integer, i.e. the memory address in which p is stored
int *pointer = &p;
printf("Pointer: %p\n", pointer);

// Dereference the pointer to get the value back
int q = *pointer;
printf("Dereferenced: %d\n", q);

给出以下输出:

Integer: 1234
Pointer: 0x7ffee53fd708
Dereferenced: 1234

还要注意,要打印出指针地址,我们必须使用特殊的格式说明符 %p,而不是用于 int%d

【讨论】:

  • 上面的代码没有任何行为,不管是讨厌的还是其他的。给定int p;,表达式*p 将无法编译。
  • 公平点 :) 我会更新我的答案。
【解决方案2】:
// declare an integer
int p = 42;

// declare a pointer type, and use it to store the address
// of the variable p. 
int* ptr = &p;

// use the * to dereference the pointer, and read the integer value
// at the address. 
int value = *ptr;

【讨论】:

    猜你喜欢
    • 2014-08-16
    • 2011-04-08
    • 2012-11-24
    • 2013-06-05
    • 2021-09-29
    • 2016-03-23
    • 2012-08-11
    • 2012-11-24
    • 2017-07-19
    相关资源
    最近更新 更多