*和&和有什么区别?在C中? [英] What's the difference between * and & in C?
问题描述
我正在学习C,但仍不确定我是否了解&
与 *
之间的区别.
I'm learning C and I'm still not sure if I understood the difference between &
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
我得到了这些,但是随后变得令人困惑.
I got these, but then it becomes confusing.
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)
和 funct(& a)
都是正确的,对吗?有什么区别?
So, both funct(*a)
and funct(&a)
are correct, right? What's the difference?
推荐答案
*
和&
作为类型修饰符
-
int i
声明一个int. -
int * p
声明了指向一个整数的指针. -
int&r = i
声明了对int的引用,并将其初始化为引用i
.
仅C ++.注意,引用必须在初始化时分配,因此int&r;
是不可能的. int i
declares an int.int* p
declares a pointer to an int.int& r = i
declares a reference to an int, and initializes it to refer toi
.
C++ only. Note that references must be assigned at initialization, thereforeint& r;
is not possible.-
void foo(int i)
声明一个带有int的函数(按值,即作为副本). -
void foo(int * p)
声明一个带有指向int指针的函数. -
void foo(int& r)
声明一个通过引用接受int的函数.(仅C ++) void foo(int i)
declares a function taking an int (by value, i.e. as a copy).void foo(int* p)
declares a function taking a pointer to an int.void foo(int& r)
declares a function taking an int by reference. (C++ only)-
foo(i)
调用foo(int)
.该参数将作为副本传递. -
foo(* p)
取消引用int指针p
并使用p指向的int调用
foo(int)
. -
foo(& i)
获取inti
的地址,并使用该地址调用foo(int *)
. li> foo(i)
callsfoo(int)
. The parameter is passed as a copy.foo(*p)
dereferences the int pointerp
and callsfoo(int)
with the int pointed to byp
.foo(&i)
takes the address of the inti
and callsfoo(int*)
with that address.-
*
可以是取消引用运算符或指针声明语法的一部分. *
can be either the dereference operator or part of the pointer declaration syntax.
*
and &
as type modifiers
类似地:
( tl; dr )因此,总而言之,取决于上下文:
(tl;dr) So in conclusion, depending on the context:
&
可以是地址运算符或引用声明语法的一部分(在C ++中).
&
can be either the address-of operator or (in C++) part of the reference declaration syntax.
请注意, *
也可能是按位AND运算符.
Note that *
may also be the multiplication operator, and &
may also be the bitwise AND operator.
这篇关于*和&和有什么区别?在C中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!