*和&和有什么区别?在C中? [英] What's the difference between * and & in C?

查看:69
本文介绍了*和&和有什么区别?在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; 是不可能的.
  • * and & as type modifiers

    • 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 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 ++)
      • 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)获取int i 的地址,并使用该地址调用 foo(int *).
      • li>
      • foo(i) calls foo(int). The parameter is passed as a copy.
      • foo(*p) dereferences the int pointer p and calls foo(int) with the int pointed to by p.
      • foo(&i) takes the address of the int i and calls foo(int*) with that address.

      ( tl; dr )因此,总而言之,取决于上下文:

      (tl;dr) So in conclusion, depending on the context:

      • * can be either the dereference operator or part of the pointer declaration syntax.

      & 可以是地址运算符或引用声明语法的一部分(在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆