我正在学习 C,但我仍然不确定我是否理解两者之间的区别&
and *
yet.
请允许我尝试解释一下:
int a; // Declares a variable
int *b; // Declares a pointer
int &c; // Not possible
a = 10;
b = &a; // b gets the address of a
*b = 20; // a now has the value 20
我得到了这些,但随后就变得混乱了。
void funct(int a) // A declaration of a function, a is declared
void funct(int *a) // a is declared as a pointer
void funct(int &a) // a now receives only pointers (address)
funct(a) // Creates a copy of a
funct(*a) // Uses a pointer, can create a pointer of a pointer in some cases
funct(&a) // Sends an address of a pointer
所以,两者funct(*a)
and funct(&a)
是正确的,对吧?有什么不同?
*
and &
as 类型修饰符
-
int i
声明一个 int。
-
int* p
声明一个pointer http://en.wikipedia.org/wiki/Pointer_(computer_programming)#C_and_C.2B.2B到一个整数。
-
int& r = i
declares a reference http://en.wikipedia.org/wiki/Reference_(C%2B%2B) to an int, and initializes it to refer to i
.
C++ only. Note that references must be assigned at initialization, therefore int& r;
is not possible.
相似地:
-
void foo(int i)
声明一个采用 int 的函数(按值,即作为副本)。
-
void foo(int* p)
声明一个带有指向 int 的指针的函数。
-
void foo(int& r)
声明一个通过引用获取 int 的函数。 (仅限 C++)
*
and &
as 运营商
-
foo(i)
calls foo(int)
。该参数作为副本传递。
-
foo(*p)
取消引用 int 指针p
并打电话foo(int)
与指向的 intp
.
-
foo(&i)
获取 int 的地址i
并打电话foo(int*)
与该地址。
(tl;dr)所以总而言之,根据上下文:
-
*
可以是解引用运算符 http://en.wikipedia.org/wiki/Dereference_operator或指针声明语法的一部分。
-
&
可以是地址运算符 http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Member_and_pointer_operators或(在 C++ 中)引用声明语法的一部分。
Note that *
may also be the multiplication operator http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Arithmetic_operators, and &
may also be the bitwise AND operator http://en.wikipedia.org/wiki/Bitwise_operation#AND.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)