-3

I have code like this

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

I do not know what to do, I just learned c language. I want to display the data dt->* that I created in main () to bar (). Firts, I have dt->* from main, I call and pass dt->* to foo1(), foo1() call foo2() and pass dt->* to foo3(). And I want to print dt->* from bar(). Please someone help me. The problem is foo3() can't update dt->* on main().

  • Are you asking how to call `bar`? Your question is not clear. – Paul Rooney Jun 10 '18 at 00:50
  • 2
    It looks like the code you posted already does that -- main() calls foo(dt), which calls bar(dt), which prints the data. If the code isn't working for you, you'll need to update your question to describe the behavior you are seeing and how it differs from the behavior you were hoping to see. – Jeremy Friesner Jun 10 '18 at 00:52
  • I've updated my question, this code is not running on my pc – user9157739 Jun 10 '18 at 01:01
  • *"I just learned c language"* -- correction *"I just began learning c"*. C isn't something you just "learn", it is something you *begin* learning and then continue learning for years to come... – David C. Rankin Jun 10 '18 at 01:22
  • Possible duplicate of [Initializing a pointer in a separate function in C](https://stackoverflow.com/questions/2486235/initializing-a-pointer-in-a-separate-function-in-c) – Bo Persson Jun 10 '18 at 10:13

1 Answers1

0

The order of your function declaration is incorrect. The main function depends on foo and foo depends on bar. Thus, you should rewrite it in the following way

#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;
}
yakobyd
  • 572
  • 4
  • 12
  • There is no need to cast the return of `malloc`, it is unnecessary. See: [Do I cast the result of malloc?](http://stackoverflow.com/q/605845/995714). `struct dta* dt = malloc (sizeof *dt);` is sufficient. And then you must validate `if (dt == NULL) { /* handle error */ }` – David C. Rankin Jun 10 '18 at 01:24