passing a structure

This is a discussion on passing a structure within the C++ Programming forums, part of the General Programming Boards category; is there a way to set up a structure in my main and then pass the entire structure to my ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    12

    passing a structure

    is there a way to set up a structure in my main and then pass the entire structure to my other functions with out passing each item individually? any help on pass structures or parts of structures is appeciated.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,794
    Yes... how you pass it depends on what you want to do with the struct within the function.

    Code:
    struct foo
    {
        // Data members go here
    };
    
    void func1(foo f)   // Passed by copy
    {
        // Do stuff with f
    }
    
    void func2(foo* f)  // Passed by pointer/reference
    {
        // Do stuff with f
    }
    
    void func3(foo& f)  // Passed by reference
    {
        // Do stuff with f
    }
    
    int main()
    {
        foo bar;
    
        func1(bar);   // Passed by copy
    
        func2(&bar);  // Passed by pointer/reference
    
        func3(bar);   // Passed by reference
    
        return 0;
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    *this
    Join Date
    Mar 2005
    Posts
    498
    why not use pointers? because every time you pass it, a copy is made.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing structure by reference or pointer?
    By 7force in forum C Programming
    Replies: 8
    Last Post: 12-13-2010, 05:49 PM
  2. Passing Structure Pointers to Functions
    By samus250 in forum C Programming
    Replies: 15
    Last Post: 03-20-2008, 03:13 PM
  3. passing structure arrays to functions?
    By bem82 in forum C Programming
    Replies: 3
    Last Post: 10-30-2006, 05:17 AM
  4. passing a structure pointer by value
    By Bleech in forum C Programming
    Replies: 6
    Last Post: 07-11-2006, 05:58 PM
  5. structure question: passing to functions
    By kocika73 in forum C Programming
    Replies: 4
    Last Post: 03-07-2005, 07:58 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21