【问题标题】:Modifying a structure passed as pointer in C修改在 C 中作为指针传递的结构
【发布时间】:2017-06-04 18:39:21
【问题描述】:

我是一个菜鸟学生,正在尝试编写一个使用二叉搜索树来组织公司员工的程序。我的老师告诉我,如果我希望能够创建 Worker 结构的新实例,我可以将 malloc 与该结构一起使用,每次使用时都会返回指向新结构的指针,然后我可以编辑该新结构的详细信息结构来自另一个函数。但是我该怎么做呢?无论我做什么,它都会变得如此复杂,我无法做到。这是我能够编写这部分代码的代码,只是为了测试我是否可以创建和编辑新结构。 我要问的主要问题是,如何编辑新创建的结构?

#include<stdlib.h>
#include<stdio.h>

struct btnode
{
    int value = 5;
    struct btnode *l;
    struct btnode *r;
};

int test(int *p)
{

    printf("%d", &p->value);
}

int main()
{
    int *asdf = (int *)malloc(sizeof(struct btnode));

    test(asdf);
}

【问题讨论】:

  • 除此之外,printf("%d", &amp;p-&gt;value); --> 是时候重新阅读本章以获得指针了。
  • int *asdf = (int *)malloc(sizeof(struct btnode)); ==> struct btnode *asdf = malloc(sizeof *asdf);
  • 我只是在测试,只是在绝望中尝试不同的东西。哦,我承认,我很难理解指针。
  • 您的老师对 C 和 C++ 之间的区别感到困惑。您不应该在 C++ 中使用 malloc。你应该使用new

标签: c pointers struct structure


【解决方案1】:

这是您程序的一个 mod,它为一个 struct 分配内存,为其成员填充值,并调用 test() 以打印一个成员。

#include <stdlib.h>
#include <stdio.h>

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
};

void test(struct btnode *p)
{
    printf("%d", p->value);
}

int main(void)
{
    struct btnode *asdf = malloc(sizeof *asdf);
    if(asdf != NULL) {
        asdf->value = 5;
        asdf->l = NULL;
        asdf->r = NULL;
        test(asdf);
        free(asdf);
    }
    return 0;
}

在细节上也有一些小的变化,我让你发现差异。

【讨论】:

    【解决方案2】:

    首先代码中有一些错误。
    1) 不能在结构中赋值。
    2)当您为结构创建指针时,您需要结构的指针而不是 int 的指针(无论您想要从结构内部获得什么)

    这是修改后的代码,可以正常运行

    #include<stdio.h>
    
    struct btnode
    {
        int value;
        struct btnode *l;
        struct btnode *r;
    };
    
    int test(struct btnode *p)
    {
    
        printf("%d", p->value);
    }
    
    int main()
    {
        struct btnode *asdf = (struct btnode*)malloc(sizeof(struct btnode));
        asdf->value = 5;
        test(asdf);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      相关资源
      最近更新 更多