Like Tree4Likes

Passing structures to a function?

This is a discussion on Passing structures to a function? within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> #include <cstdlib> #include <ctime> using namespace std; struct Spaceship; Spaceship move_ship(Spaceship ship); void update_location(Spaceship ship, int &count); ...

  1. #1
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77

    Passing structures to a function?

    Code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    
    using namespace std;
    
    
    
    
    struct Spaceship;
    Spaceship move_ship(Spaceship ship);
    void update_location(Spaceship ship, int &count);
    Spaceship get_new_ship(Spaceship ship);
    
    
    
    
    struct Spaceship
    {
        int x_coordinate;
        int y_coordinate;
    };
    
    
    
    
    Spaceship get_new_ship()
    {
        Spaceship ship;
    
    
        ship.x_coordinate = 0;
        ship.y_coordinate = 0;
    
    
       return ship;
    }
    
    
    
    
    
    
    
    
    void update_location(Spaceship ship,int &count)
    {
    
    
    
    
            std::cout << "Ship is now located at (" << ship.x_coordinate << "," << ship.y_coordinate << ")." << endl;
            if (ship.x_coordinate > 1024 || ship.y_coordinate > 768)
            {
                std::cout << "Ship has left the screen. \n";
                count = 0;
    
    
             }
    }
    
    
    
    
    
    
    int main()
    {
        int count = 1;
    
        Spaceship ship = get_new_ship();
    
    
        do{
    
    
        ship.x_coordinate = ship.x_coordinate + 10;
        ship.y_coordinate = ship.y_coordinate + 10;
    
    
        update_location(ship,count);
    
    
    
    
        }
        while(count != 0);
    
    
    }
    I've managed to output all the ship's location after it make each 10 units movement towards north east using the code above, without putting the 'add 10 coordinates' in a function.

    However if I put it this way (put it in the function Spaceship move_ship(), coordinate x and y remains zero. What is wrong with my function? ):

    Code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    
    using namespace std;
    
    
    
    
    struct Spaceship;
    Spaceship move_ship(Spaceship ship);
    void update_location(Spaceship ship, int &count);
    Spaceship get_new_ship(Spaceship ship);
    
    
    
    
    struct Spaceship
    {
        int x_coordinate;
        int y_coordinate;
    };
    
    
    
    
    Spaceship get_new_ship()
    {
        Spaceship ship;
    
    
        ship.x_coordinate = 0;
        ship.y_coordinate = 0;
    
    
       return ship;
    }
    
    
    
    
    
    
    Spaceship move_ship(Spaceship ship)
    {
    
    
    
    
            ship.x_coordinate = ship.x_coordinate + 10;
            ship.y_coordinate = ship.y_coordinate + 10;
    
    
        return ship;
    
    
    
    
    }
    
    
    void update_location(Spaceship ship,int &count)
    {
    
    
    
    
            std::cout << "Ship is now located at (" << ship.x_coordinate << "," << ship.y_coordinate << ")." << endl;
            if (ship.x_coordinate > 1024 || ship.y_coordinate > 768)
            {
                std::cout << "Ship has left the screen. \n";
                count = 0;
    
    
             }
    }
    
    
    
    
    
    
    int main()
    {
        int count = 1;
    
    
        Spaceship ship = get_new_ship();
    
    
        do{
    
    
        move_ship(ship);
        update_location(ship,count);
    
    
    
    
        }
        while(count != 0);
    
    
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,647
    Quote Originally Posted by Meerul264
    However if I put it this way (put it in the function Spaceship move_ship(), coordinate x and y remains zero. What is wrong with my function? ):
    You pass the Spaceship by value, i.e., you modify a copy of the Spaceship in the function, hence it appears from the caller that nothing has changed. One way out is to pass by reference:
    Code:
    Spaceship move_ship(Spaceship& ship)
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77
    Thanks. But what about this? He doesn't use reference?

    Is it because he does it only once?

    Code:
    struct EnemySpaceShip {
     int x_coordinate; int y_coordinate; int weapon_power;}; 
    
    
    EnemySpaceShip getNewEnemy{
     EnemySpaceShip ship; ship.x_coordinate = 0;
    
    
     ship.y_coordinate = 0;
     ship.weapon_power = 20;
     return ship;
    }
    
    
    EnemySpaceShip upgradeWeapons (EnemySpaceShip ship){
     ship.weapon_power += 10; return ship;
    }
    
    
    int main ()
    {
     EnemySpaceShip enemy = getNewEnemy(); enemy = upgradeWeapons( enemy );
    
    }

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,647
    Quote Originally Posted by Meerul264
    But what about this? He doesn't use reference?

    Is it because he does it only once?
    No, because the function returns the copy of the object.

    By the way, you need to indent your code properly. Typically, each statement should go in its own line, with a certain number of spaces (> 1) or a tab per indent level. For example:
    Code:
    struct EnemySpaceShip
    {
        int x_coordinate;
        int y_coordinate;
        int weapon_power;
    };
    
    EnemySpaceShip getNewEnemy
    {
        EnemySpaceShip ship;
        ship.x_coordinate = 0;
        ship.y_coordinate = 0;
        ship.weapon_power = 20;
        return ship;
    }
    
    EnemySpaceShip upgradeWeapons(EnemySpaceShip ship)
    {
        ship.weapon_power += 10;
        return ship;
    }
    
    int main()
    {
        EnemySpaceShip enemy = getNewEnemy();
        enemy = upgradeWeapons(enemy);
    }
    Elysia likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77
    One more related question:

    What's the difference between

    Code:
     Spaceship move_ship(Spaceship& ship) 


    and

    Code:
    Spaceship move_ship(Spaceship &ship) 


    ?

    One is attached to the type, and another one is attached to the variable. They means the same?

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,647
    Quote Originally Posted by Meerul264
    One is attached to the type, and another one is attached to the variable. They means the same?
    The whitespace is not significant here, so they mean the same thing. However, I prefer to position the & next to the type name to emphasize type. Refer to: Is ``int* p;'' right or is ``int *p;'' right?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,667
    Whitespace does not matter in many C++ "places." Many of the places it does matter were inherited from C. In addition to that you need to consider:

    That templates arguments which contain templates themselves need special spacing, e.g.
    Code:
    vector< vector<char> > 2dbytesvec;
    That // C++ comments end on a new line.

    Other than that you may cram up as many operators or type names without much regard for white space (but keep it human readable). If anything, C++ makes a distinction on what type something is by switching the order of adornments, instead. A reference to a pointer of char is char*& type, whereas the other type char&* is not ok and will make a compiler error show up.

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    6,261
    Quote Originally Posted by whiteflags View Post
    That templates arguments which contain templates themselves need special spacing, e.g.
    Code:
    vector< vector<char> > 2dbytesvec;
    That need changed with C++-11.
    Elysia likes this.
    Right 98% of the time, and don't care about the other 3%.

  9. #9
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77
    Now I want to do the same thing as above, but this time it is an array of space ship objects, instead of just one. Is it possible to pass them by reference and do the coding same as above, but now I change the spaceship ship to spaceship ship[5] ?

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,647
    Quote Originally Posted by Meerul264
    Now I want to do the same thing as above, but this time it is an array of space ship objects, instead of just one. Is it possible to pass them by reference and do the coding same as above, but now I change the spaceship ship to spaceship ship[5] ?
    The array would be converted to a pointer to its first element, so you don't need to pass it by reference. However, if you are using std::array instead, then you should pass it by reference.
    Elysia likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77
    Sorry what do you mean by using std::array?

    Anyway, I change the code a little, but I don't know what's wrong. I'll post the compiler error along with the code.

    Code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    
    using namespace std;
    
    
    struct Spaceship;
    Spaceship move_ship(Spaceship ship[], int i);
    void update_location(Spaceship ship[],int i,int &count);
    Spaceship get_new_ship(Spaceship ship[]);
    
    
    struct Spaceship
    {
        int x_coordinate;
        int y_coordinate;
    };
    
    
    Spaceship get_new_ship()
    {
        Spaceship ship[5];
    
    
        for(int i=0;i<5;i++)
        {
        ship[i].x_coordinate = 0;
        ship[i].y_coordinate = 0;
        }
    
    
    }
    
    
    Spaceship move_ship(Spaceship ship[], int i)
    {
        ship[i].x_coordinate = ship[i].x_coordinate + rand()%150;
        ship[i].y_coordinate = ship[i].y_coordinate + rand()%140;
    }
    
    
    void update_location(Spaceship ship[],int i, int &count)
    {
        std::cout << "Ship is now located at (" << ship[i].x_coordinate << "," << ship[i].y_coordinate << ")." << endl;
        if (ship[i].x_coordinate > 1024 || ship[i].y_coordinate > 768)
        {
            std::cout << "Ship has left the screen. \n";
            count--;
        }
    }
    
    
    int main()
    {
        int count = 5;
        
        srand(time(0));
    
    
        for(int i=0;i<5;i++)
        {
            Spaceship ship[i] = get_new_ship();
            Spaceship new_ship[i] = move_ship(ship,i);
            update_location(new_ship,i,count);
        }
    }
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp||In function 'Spaceship get_new_ship()':|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp|30|warning: no return statement in function returning non-void|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp||In function 'Spaceship move_ship(Spaceship*, int)':|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp|38|warning: no return statement in function returning non-void|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp||In function 'int main()':|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp|60|error: variable-sized object 'ship' may not be initialized|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp|61|error: variable-sized object 'new_ship' may not be initialized|
    ||=== Build finished: 2 errors, 2 warnings ===|

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,647
    Quote Originally Posted by Meerul264
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp||In function 'Spaceship get_new_ship()':|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp|30|warning: no return statement in function returning non-void|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp||In function 'Spaceship move_ship(Spaceship*, int)':|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp|38|warning: no return statement in function returning non-void|
    The above error messages are informing you that you forgot about your return statements.

    Quote Originally Posted by Meerul264
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp||In function 'int main()':|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp|60|error: variable-sized object 'ship' may not be initialized|
    C:\Program Files (x86)\CodeBlocks\Projects\Space ship moving\main.cpp|61|error: variable-sized object 'new_ship' may not be initialized|
    This one is a little harder to explain. The thing is, this looks like an attempt to declare and initialise a variable length array:
    Code:
    Spaceship ship[i] = get_new_ship();
    same for this line:
    Code:
    Spaceship new_ship[i] = move_ship(ship,i);
    Now, variable length arrays are a compiler extension: they are not part of standard C++. The problem here is that you did not declare your array in the main function; your declared it in get_new_ship, but that's a wrong place. Actually, you don't need the get_new_ship function. Rather, write a default constructor for the Spaceship class.
    Lesshardtofind likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77
    I don't know what default constructor is, never heard of it. In which chapter is it? But anyway I just put it like this;


    Code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    
    
    
    using namespace std;
    
    
    struct Spaceship
    {
        int x_coordinate;
        int y_coordinate;
    };
    
    
    int main()
    {
        int count = 6;
        int i = 0;
        srand(time(0));
    
    
        Spaceship ship[5];
    
    
        for(int i =0;i<5;i++)
        {
        ship[i].x_coordinate = 0;
        ship[i].y_coordinate = 0;
        }
    
    
        do
        {
        for(int i=0;i<5;i++)
        {
    
    
    
    
        ship[i].x_coordinate = ship[i].x_coordinate + rand()%150;
        ship[i].y_coordinate = ship[i].y_coordinate + rand()%140;
    
    
        std::cout << "Ship " << i+1 << " is now located at (" << ship[i].x_coordinate << "," << ship[i].y_coordinate << ")." << endl <<endl;
        if (ship[i].x_coordinate > 1024 || ship[i].y_coordinate > 768)
        {
            std::cout << "Ship " << i+1 << " has left the screen. \n\n";
            count--;
    
    
            if (count == 0)
            {
                std::cout << "All ship has left the screen. \n\n";
            }
        }
    
    
        }
        }
        while(count !=0);
    
    
    }
    So I really can't use function for this?

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,647
    No, you can write functions, but you need to write them right.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77
    If you wouldn't mind I'd like to see an example.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing structures to a function
    By Magi in forum C Programming
    Replies: 7
    Last Post: 12-05-2012, 02:04 PM
  2. Passing Structures as Function Arguments
    By Jyqft in forum C Programming
    Replies: 13
    Last Post: 03-26-2012, 08:02 AM
  3. Structures, passing array of structures to function
    By saahmed in forum C Programming
    Replies: 10
    Last Post: 04-05-2006, 11:06 PM
  4. Passing structures to a function
    By earth_angel in forum C++ Programming
    Replies: 5
    Last Post: 07-13-2005, 06:13 AM
  5. passing array of structures to function
    By bvnorth in forum C Programming
    Replies: 3
    Last Post: 08-22-2003, 07:15 AM

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