Thread: passing struct pointer to function.

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    10

    passing struct pointer to function.

    Hello, I am trying to write a function that will take a struct pointer and some other values defined in the struct and within the function allocate memory for the struct and pass the values to it. How can this be done in C?


    Here is some example code that does not work:

    Code:
    struct a
    {
       int a;
       long b;
       char buf[32];
    }
    
    
    void createNode(struct a* x, int y, long z, char *mesg);
    int main()
    {
       struct a* x;
       int a=1;
       long b=2.0;
       char *msg = "This is a test";
    
    
       createNode(&x, a, b, msg);
    }
    
    
    void createNode(struct a* x, int y, long z, char *mesg)
    {
       x=malloc(sizeof(struct a));
       x->a = y;
       x->b = z;
       strcpy(x->buf, mesg)
    }
    

  2. #2
    Registered User
    Join Date
    Oct 2011
    Location
    Denmark
    Posts
    80
    Hello,

    Take a look at what your sending to your function and what you are expecting to receive, you should see there is a problem.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You can't update the variable a value you pass belongs to without passing a pointer to that value. You need to pass a pointer to your pointer. Alternately, you can return the new node, and assign the return value.


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User
    Join Date
    Oct 2011
    Posts
    10
    Thank you for the replies I see my misunderstanding

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 05-12-2011, 01:02 AM
  2. Replies: 5
    Last Post: 05-04-2010, 11:43 PM
  3. Passing a struct via pointer question
    By Thantos in forum C Programming
    Replies: 3
    Last Post: 11-29-2003, 06:54 PM
  4. Passing Pointer-to-struct to a function!!
    By Lau in forum C Programming
    Replies: 5
    Last Post: 11-18-2002, 12:59 PM
  5. Passing a pointer to a struct
    By Natase in forum C Programming
    Replies: 2
    Last Post: 10-02-2001, 10:29 AM