& 和 * 之间的区别

Difference between & and *

本文关键字:区别 之间      更新时间:2023-10-16

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

前任。

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

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

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

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

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

请考虑以下事项:

// Create an integer
int p = 1234;
printf("Integer: %dn", p);
// Get the pointer to that integer, i.e. the memory address in which p is stored
int *pointer = &p;
printf("Pointer: %pn", pointer);
// Dereference the pointer to get the value back
int q = *pointer;
printf("Dereferenced: %dn", q);

提供以下输出:

Integer: 1234
Pointer: 0x7ffee53fd708
Dereferenced: 1234

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

// 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;