我刚刚开始使用指针,我有点困惑.我知道&
表示变量的地址,*
可以用在指针变量的前面,以获取指针指向的对象的值.但是,当您使用数组、字符串或使用变量的指针副本调用函数时,情况会有所不同.很难看出这一切背后的逻辑模式.
我应该什么时候使用&
和*
?
我刚刚开始使用指针,我有点困惑.我知道&
表示变量的地址,*
可以用在指针变量的前面,以获取指针指向的对象的值.但是,当您使用数组、字符串或使用变量的指针副本调用函数时,情况会有所不同.很难看出这一切背后的逻辑模式.
我应该什么时候使用&
和*
?
你有指针和值:
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