使用箭头->和点 . C 中的运算符在一起

发布于 2024-11-04 04:17:46 字数 298 浏览 1 评论 0原文

我的印象是,可以通过像这样一起使用箭头和点运算符来从链表或类似结构的子节点访问数据:

typedef struct a{
int num;
struct a *left;
struct a *right;
}tree;

tree *sample;
...
if(sample->left.num > sample->right.num)
    //do something

但是当我尝试实现这一点时,使用 ->;和 。要从子节点访问数据,我收到错误“请求非结构或联合中的成员 num”。

I was under the impression that it was possible to access data from a sub-node of a linked list or similar structure by using the arrow and dot operators together like so:

typedef struct a{
int num;
struct a *left;
struct a *right;
}tree;

tree *sample;
...
if(sample->left.num > sample->right.num)
    //do something

but when I try to implement this, using -> and . to access data from a sub node I get the error "request for member num in something not a structure or union".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

扎心 2024-11-11 04:17:46

使用 -> 作为指针;使用 . 表示对象。

在您的具体情况下,您需要

if (sample->left->num > sample->right->num)

,因为所有 samplesample->leftsample->right 都是指针。

如果您转换指向对象中的任何指针;使用 . 代替

struct a copyright;
copyright = *(sample->right);
// if (sample->left->num > copyright.num)
if (*(sample->left).num > copyright.num)

Use -> for pointers; use . for objects.

In your specific case you want

if (sample->left->num > sample->right->num)

because all of sample, sample->left, and sample->right are pointers.

If you convert any of those pointers in the pointed to object; use . instead

struct a copyright;
copyright = *(sample->right);
// if (sample->left->num > copyright.num)
if (*(sample->left).num > copyright.num)
梦里人 2024-11-11 04:17:46

因为我没有看到明确提到它:

  • 使用 -> 取消引用其左侧的指针并访问其右侧的成员。
  • 使用 。访问左侧变量右侧的成员。

Since I don't see it mentioned explicitly:

  • Use -> to dereference the pointer on its left hand side and access the member on its right hand side.
  • Use . to access the member on its right hand side of the variable on its left hand side.
初懵 2024-11-11 04:17:46

。用于访问结构(或联合)的成员,例如

struct S {
int x;
}

S test;
test.x;

->是一种更短的写法 (*pointer_to_struct).struct_member

. is for accessing the members of a struct (or union) e.g.

struct S {
int x;
}

S test;
test.x;

-> is a shorter way to write (*pointer_to_struct).struct_member

千寻… 2024-11-11 04:17:46

Sample->left 给出一个 struct a*,而不是一个 struct a,所以我们处理的是指针。
所以你还是要使用->

不过,您可以使用sample->left->num

sample->left gives a struct a*, not a struct a, so we're dealing with pointers.
So you still have to use ->.

You can, however, use sample->left->num.

抽个烟儿 2024-11-11 04:17:46

sample->leftsample->right 也是指针,所以你想要:

if (sample->left->num > sample->right->num) {
    // do something
}

sample->left and sample->right are also pointers, so you want:

if (sample->left->num > sample->right->num) {
    // do something
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文