Coming from Java I was trying to implement a simple Battleships game in C++ but already got stuck at this Array:
#include <iostream>
#include <utility>
using namespace std;
class Ship{
private:
int length;
bool direction; //false = left, true = down
pair <int,int> coords[];
public:
Ship(int x, int y, bool, int);
void printship();
};
Ship::Ship(int x, int y, bool dir, int l){
pair <int,int> coords[l];
length = l;
if (dir){
for (int i = 0; i < l; i++){
coords[i] = make_pair(x, y+i);
}
}
else{
for (int i = 0; i < l; i++){
coords[i] = make_pair(x+i, y);
}
}
}
void Ship::printship(){
for (int i = 0; i < length; i++){
cout << "x: " << coords[i].first << ", y: " << coords[i].second << endl;
}
}
int main(){
Ship tests(2,3,true,3);
tests.printship();
return 0;
}
What I get is:
x: 134515168, y: 0
x: 0, y: 9938131
x: 1, y: -1080624940
I guess something is pointing to unallocated memory, but I can’t figure out what, and why.
You have two different variables both called
coords. One is a private member variable, the other is local to the constructor. Because the local variable you create in the constructor shadows the member variable, the constructor never initializes the member variable.Try this instead: