0

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_ */
0

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

You're simply printing the first letter P. No memory allocation to hold the array as well.
This code may compile if your compiler is old and allows C++9X or C++03 stuff. In the new compiler you will get an error because example = "PASS"; tries to write a const char * into char *, completely dropping the const.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.