传递struct的指针

时间:2018-06-10 00:46:57

标签: c

我有这样的代码

的main.c

....
....
struct dta
{
    int id;
    char *val;
};
....
....
int main(void)
{
    struct dta *dt = malloc(sizeof(*dt));
    dt->id=8;
    dt->val=strdup("123456qwerty");

    foo1(dt);

    free(.........);
    free(.........);

    return 0;

 }

void foo1(struct dta *dt)
{
    foo2(dt);
}

void foo2(struct dta *dt)
{
    foo3(dt);
}

void foo3(struct dta *dt)
{
    free(dt->val);
    dt->val=strdup("asdfg123456");
    dt->id=18;
    bar(dt);
}

void bar(struct dta *dt)
{
    printf("id = %d\n", dt->id);
    printf("val = %s\n", dt->val);
}

我不知道该怎么做,我刚刚学会了c语言。我想将我在main()中创建的数据dt-> *显示为bar()。 Firts,我有来自main的dt->; *我调用并传递dt-> *到foo1(),foo1()调用foo2()并将dt-> *传递给foo3()。我想从bar()打印dt-> *。请有人帮助我。问题是foo3()无法在main()上更新dt-> *。

1 个答案:

答案 0 :(得分:0)

您的函数声明的顺序不正确。 main函数取决于foofoo取决于bar。因此,您应该按以下方式重写它

#include <malloc.h>  // for malloc and free
#include <stdio.h>  // for printf
#include <string.h>  // for strdup

struct dta
{
    int id;
    char* val;
};

void bar(struct dta* dt)
{
    printf("id = %d\n", dt->id);
    printf("val = %s\n", dt->val);
}

void foo(struct dta* dt)
{
    bar(dt);
}

int main()
{
    struct dta* dt = (struct dta*) malloc(sizeof(struct dta));
    dt->id = 8;
    dt->val = strdup("123456qwerty");

    foo(dt);

    // Free allocated memory
    free(dt->val);
    free(dt);

    return 0;
}
相关问题