Thread: Structs as argument

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    31

    Structs as argument

    Hi I want to pass in a struct as an argument in a function, in which this function pass the same struct to another function.

    Code:
    StructExample tyExample;
    
    void function1(&tyExample);
    Then in my function 1 which looks like this

    Code:
    void function1(StructExample* tyExample)
    {
        function2(tyExample);
    }
    Then my function 2 looks like this

    Code:
    void function2(StructExample* tyExample)
    {
       //some code to fill in tyExample
    }
    Is this the correct way to pass structs as arugment to different functions?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    As long as you're aware that the names don't have to be the same (they can be if you want, but it can lead to confusion).

    As to the question, I have no idea why you would expect passing a struct to a function to be different from passing a struct to a function. (EDIT: But I suppose I should say that you are correct: passing a struct to a function is not different from passing a struct to a function, so your code is fine.)

  3. #3
    Registered User
    Join Date
    Aug 2011
    Posts
    31
    oh. I saw this example about char* pointers, hence the question about structs

    Code:
    int my_new(char **obj) {
        *obj = malloc(somesize);
    }
    and then call this from your function like this:

    Code:
    char *obj;
    
    my_new(&obj);
    
    /* work on obj */
    
    free(obj)
    Hence was wondering if it applies to structs

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    I don't see how that is related to your original question at all. (Edit: Even if obj comes in as a parameter rather than a declaration, you are given a string and passing a pointer-to-string; in your original question both arguments are pointer-to-struct.)

  5. #5
    Registered User
    Join Date
    Aug 2011
    Posts
    31
    oh i see i see. Thanks for the clarifications! =)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Argument inside the Argument of a Function Declaration
    By manasij7479 in forum C++ Programming
    Replies: 3
    Last Post: 06-11-2011, 05:53 AM
  2. [ noob question ] Help with structs within structs
    By Riverfoot in forum C Programming
    Replies: 3
    Last Post: 04-26-2011, 07:24 PM
  3. Passing Structs Into An Array Of Structs.
    By TheTaoOfBill in forum C Programming
    Replies: 3
    Last Post: 10-07-2010, 09:38 AM
  4. Replies: 3
    Last Post: 03-31-2009, 12:34 PM
  5. passing structs & pointers to structs as arguments
    By Markallen85 in forum C Programming
    Replies: 6
    Last Post: 03-16-2004, 07:14 PM