Reputation: 31
I try to print an array and I can not. Does anyone have any idea why ?
In the Main.cpp file there is of course a function call.
My code:
Game.cpp:
#include "Game.h"
Game::Game() {
char example[] = "PASS";
}
bool Game::PrintArray() {
cout << example[0] << endl;
return true;
}
Game.h:
#include <iostream>
#include <array>
#include <iostream>
#include <string>
using namespace std;
#ifndef GAME_H_
#define GAME_H_
class Game {
private:
char example[];
public:
Game();
bool PrintArray();
};
#endif /* GAME_H_ */
Upvotes: 0
Views: 195
Reputation: 485
Your code has three problems:
1) Array example in Game.h is a static array of zero length (so you can't add characters there) Solution: make a const pointer to an array of characters
2) Inside the Game's constructor you create a NEW variable example, do not affect the variable in the Game.h -> your variable in the class just don't updated
solution: example = "PASS";
3) In func Game::PrintArray you are printing only first character
Solution: cout << example << endl;
Game.h:
class Game {
private:
const char* example;
public:
Game();
bool PrintArray();
};
Game.cpp:
Game::Game() {
example = "PASS";
}
bool Game::PrintArray() {
cout << example << endl;
return true;
}
But even more correct solution is to use std::string
. Then you don't have to worry about allocated/unallocated memory:
Game.h:
class Game {
private:
std::string example;
public:
Game();
bool PrintArray();
};
Game.cpp:
Game::Game() {
example = "PASS";
}
bool Game::PrintArray() {
cout << example << endl;
return true;
}
Upvotes: 2