It's not displaying correctly, am I using the pointers for callsign and location correctly?

/*
This program creates 2 instances of a dynamic memory data structure that represents spaceships that are located at random coords in 2 dimensions.
The program will loop, assigning new coords to the ships until the ships are within 10, at which point a "collision" has occured. It will report
the callsign (name of ship), location, and the loop count when the collision occurs.
*/

#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;

struct spaceship { // create the ship
int x, y;
char callsign[51];
};

void shiprandomlocation(spaceship *ship, int maxlocation) { //randomize location
ship->x = rand() % maxlocation;
ship->y = rand() % maxlocation;
}

int shipdetectcollision(spaceship *ship1, spaceship *ship2, float collidingrange) { //determain if the ships collide
if (collidingrange<10) {
return 1;
}
else {
return 0;
}
}

int main()
{
int maxlocation = 100, collidingrange = 10;
int numberofloops;
cout << "Enter the Number of Collisions to Simulate: ";
cin >> numberofloops;
for (int i = 0; i < numberofloops; i++) {
int loopcount = 0;
float d;
spaceship *ship1, *ship2;
ship1 = new spaceship;
ship2 = new spaceship;
strcpy_s(ship1->callsign, "XWing");
strcpy_s(ship2->callsign, "Falcon");
d = sqrt((ship1->x - ship2->x)*(ship1->y - ship2->y)); //find distance between the two ships.
while (!shipdetectcollision(ship1, ship2, collidingrange)) {
shiprandomlocation(ship1, maxlocation);
shiprandomlocation(ship2, maxlocation);
++loopcount;
}
delete ship1, ship2; //delete the dynamic memory structure
}
cout << "Callsign: " << ship->callsign << endl;
cout << "Location: " << ship->x << ", " << ship->y << endl;
cout << "Loop: " << loopcount << endl;
return 0;
}
What does it do that you don't like, and what does it not do that you wish it did?

While I'm here, don't use char arrays. Use string.
This will also allow you to stop using strcpy.

There is no reason in this code to be use new or delete, so don't do that.
xxmahowardxx,
This piece of code will give errors because. ship was never defined, essentially the program has no idea what a ship is.
1
2
3
cout << "Callsign: " << ship->callsign << endl;
cout << "Location: " << ship->x << ", " << ship->y << endl;
cout << "Loop: " << loopcount << endl;

Last edited on
tibrado, can you please delete your post in http://www.cplusplus.com/forum/general/242296/
That's a spambot you're replying to.
Also, in the future you should turn on your Private Messaging.

(I'll delete this post once I see you were successfully able to delete your post)
Last edited on
@Ganado I wondered what that link was about lol.
Topic archived. No new replies allowed.