我正在读一本叫做《21天自学C语言》的书(我已经学会了Java和c#,所以我正在以更快的速度前进)。我正在阅读关于指针的章节,->(箭头)操作符没有解释就出现了。我认为它是用来调用成员和函数的(类似于。(点)操作符,但用于指针而不是成员)。但我不完全确定。

我能得到一个解释和一个代码样本吗?


当前回答

我只想在答案中加上一个“为什么”。

. 标准成员访问操作符,其优先级高于*指针操作符。

当你试图访问一个结构的内部,你把它写成*foo。Bar然后编译器会认为需要一个'foo'(内存中的地址)的' Bar '元素,显然这个地址没有任何成员。

因此,你需要要求编译器先对(*foo)解引用,然后访问成员元素:(*foo)。Bar,写起来有点笨拙,所以好事者想出了一个简写版本:foo-> Bar,这是一种指针操作符的成员访问。

其他回答

是的,就是这样。

它只是点版本,当你想访问一个结构/类的元素是一个指针,而不是一个引用。

struct foo
{
  int x;
  float y;
};

struct foo var;
struct foo* pvar;
pvar = malloc(sizeof(struct foo));

var.x = 5;
(&var)->y = 14.3;
pvar->y = 22.4;
(*pvar).x = 6;

就是这样!

在某些情况下,->操作符使代码比*操作符更具可读性。

如:(引自EDK II项目)

typedef
EFI_STATUS
(EFIAPI *EFI_BLOCK_READ)(
  IN EFI_BLOCK_IO_PROTOCOL          *This,
  IN UINT32                         MediaId,
  IN EFI_LBA                        Lba,
  IN UINTN                          BufferSize,
  OUT VOID                          *Buffer
  );


struct _EFI_BLOCK_IO_PROTOCOL {
  ///
  /// The revision to which the block IO interface adheres. All future
  /// revisions must be backwards compatible. If a future version is not
  /// back wards compatible, it is not the same GUID.
  ///
  UINT64              Revision;
  ///
  /// Pointer to the EFI_BLOCK_IO_MEDIA data for this device.
  ///
  EFI_BLOCK_IO_MEDIA  *Media;

  EFI_BLOCK_RESET     Reset;
  EFI_BLOCK_READ      ReadBlocks;
  EFI_BLOCK_WRITE     WriteBlocks;
  EFI_BLOCK_FLUSH     FlushBlocks;

};

_EFI_BLOCK_IO_PROTOCOL结构体包含4个函数指针成员。

假设你有一个变量结构_EFI_BLOCK_IO_PROTOCOL * pStruct,你想使用老的*操作符来调用它的成员函数指针。你最终会得到这样的代码:

(* pStruct) .ReadBlocks参数(……)

但是使用->操作符,你可以这样写:

pStruct - > ReadBlocks参数(……)。

哪个看起来更好?

#include<stdio.h>
struct examp{
int number;
};
struct examp a,*b=&a;`enter code here`
main()
{
a.number=5;
/* a.number,b->number,(*b).number produces same output. b->number is mostly used in linked list*/
   printf("%d \n %d \n %d",a.number,b->number,(*b).number);
}

输出是5 5个5

Foo ->bar等价于(* Foo)。Bar,即它从foo指向的结构体中获取名为Bar的成员。

Foo ->bar只是(* Foo).bar的简写。这就是它的全部。