Odd Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <ctime>
#include <cstdlib>

struct enemySpaceShip
{
    int xCoord;
    int yCoord;
    int shipNumber;
};

void displayShips(enemySpaceShip ship[])
{
    for (int i = 0; i < 5; i++)
    {
        std::cout << "Enemy ship = " << ship[i].shipNumber << std::endl;
        std::cout << "X coord = " << ship[i].xCoord << std::endl;
        std::cout << "Y coord = " << ship[i].yCoord << std::endl;
        std::cout << std::endl << std::endl;
    }
    return;
}

int main()
{
    srand(time(NULL));
    enemySpaceShip ship[5];

    for (int i = 0; i < 5; i++)
    {
        ship[i].xCoord = (rand() % 1024);
        ship[i].yCoord = (rand() % 768);
        ship[i].shipNumber = ++i;
    }
    displayShips(ship);


}


Output:

Enemy ship = 1
X coord = 0
Y coord = 4286272


Enemy ship = 1994427605
X coord = 329
Y coord = 68


Enemy ship = 3
X coord = -387908129
Y coord = -2


Enemy ship = 2686868
X coord = 384
Y coord = 500



Why am I getting such odd outputs, not just for the coords, but the ship numbers.
You are increasing `i' twice in each iteration of the loop, so you miss some elements that remain uninitialised.

Also, I think that ship[i].shipNumber = ++i; is undefined behaviour
http://en.cppreference.com/w/cpp/language/eval_order
Last edited on
Line 33:
1
2
3
// ship[i].shipNumber = ++i; // engenders undefined behaviour
                             // even if it didn't, it would interfere with the index
ship[i].shipNumber = i + i ;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <ctime>
#include <cstdlib>

struct enemySpaceShip
{
    int xCoord;
    int yCoord;
    int shipNumber;
};

void displayShips( enemySpaceShip ship[], int nships )
{
    for( int i = 0; i < nships ; ++i )
    {
        std::cout << "Enemy ship = " << ship[i].shipNumber // << std::endl;
                  << "\nX coord = " << ship[i].xCoord // << std::endl;
                  << "\nY coord = " << ship[i].yCoord // << std::endl;
                  << "\n\n\n" ; // std::endl << std::endl;
    }
    //return;
}

int main()
{
    std::srand( std::time(nullptr) );
    const int NSHIPS = 5 ;
    const int XSIZE = 1024 ;
    const int YSIZE = 768 ;

    enemySpaceShip ship[NSHIPS];

    for( int i = 0; i < NSHIPS ; ++i ) ship[i] = { std::rand()%XSIZE, std::rand()%YSIZE, i+1 } ;

    displayShips( ship, NSHIPS );
}

http://coliru.stacked-crooked.com/a/69f8c87ad0a3ea46
Topic archived. No new replies allowed.