我有这样的代码
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 ()。首先,我从main调用dt->*并将其传递给foo1(),foo1()调用foo2()并将dt->*传递给foo3()。我想从bar()打印dt->*。请谁来帮帮我。问题是foo3()不能更新main()上的dt->*。
发布于 2018-06-10 09:15:57
函数声明的顺序不正确。main
函数依赖于foo
,foo
依赖于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;
}
https://stackoverflow.com/questions/50779707
复制相似问题