gpt4 book ai didi

c - C 中的指针 : when to use the ampersand and the asterisk?

转载 作者:太空狗 更新时间:2023-10-29 16:13:39 24 4
gpt4 key购买 nike

我刚开始使用指针,我有点困惑。我知道 & 表示变量的地址, * 可以用在指针变量的前面来获取指针指向的对象的值。但是,当您使用数组、字符串或使用变量的指针副本调用函数时,情况就不同了。很难在所有这些内容中看到逻辑模式。

什么时候应该使用&*

最佳答案

你有指针和值:

int* p; // variable p is pointer to integer type
int i; // integer value

你用*把一个指针变成一个值:

int i2 = *p; // integer i2 is assigned with integer value that pointer p is pointing to

你用&把一个值变成一个指针:

int* p2 = &i; // pointer p2 will point to the address of integer i

编辑:对于数组,它们的处理方式非常像指针。如果您将它们视为指针,您将使用 * 获取它们内部的值,如上文所述,但还有另一种更常见的方式使用 [] 运算符:

int a[2];  // array of integers
int i = *a; // the value of the first element of a
int i2 = a[0]; // another way to get the first element

获取第二个元素:

int a[2]; // array
int i = *(a + 1); // the value of the second element
int i2 = a[1]; // the value of the second element

所以 [] 索引运算符是 * 运算符的一种特殊形式,它的工作原理如下:

a[i] == *(a + i);  // these two statements are the same thing

关于c - C 中的指针 : when to use the ampersand and the asterisk?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2094666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com