结构指针地址比较不起作用

标签 c pointers struct

如果 findset 中的条件没有给出正确的比较。它总是显示不相等。

我哪里做错了?

#include<stdio.h>

struct node {
  struct node *p;
  int rank;
};

void makeset(struct node x) {
  x.p = &x;
  x.rank = 0;
}

void findset(struct node x) {
  if (x.p == &x) {
    printf("It worked bro\n");
  }
}

int main() {
  int nv, ne;
  nv = 4;
  ne = 5;
  for (int i = 0; i < nv; ++i) {
    struct node i;
    makeset(i);
    findset(i);
  }
}

最佳答案

void findset(struct node x)
 {
    if (x.p == &x)
    {

x 是传入地址的副本...x 始终是全新的,&x 不会匹配任何以前的地址。

请注意,这不仅适用于结构,而且适用于所有值...

int i = 3;

void f( int j)
{
    // &j != &i
    // j == i
    // j and I have the same value, but different address
}

int main()
{
   f(i);
}

关于结构指针地址比较不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49703313/

相关文章:

C++ 继承 : Derived class pointer to a Base class invokes Derived class method

将字节复制到结构会给出错误的值

c - 接收错误 - 请求成员 ****** 不是结构或 union

c - 将数据从文件写入 C 上的结构

c - 生成 RTE_Components.h

将int数组转换为c中的int值

c++ - 在 C++ 中返回对象或指针

c++ - Word 解读程序 - C++

c++ - 为嵌入式 C/C++ 项目构建系统

android - 使用 Android NDK 中的系统函数在 Android 嵌入式设备上运行 Shell 脚本文件