修改在C中作为指针传递的结构

时间:2017-06-04 18:39:22

标签: c pointers struct structure

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

#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);
}

2 个答案:

答案 0 :(得分:3)

以下是程序的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;
}

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

答案 1 :(得分:0)

首先,代码中存在一些错误 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);
}
相关问题