I learned how to pass an array (of integers) in a function and also know how to do it in a constructor. But when I access the array in the object I just created, the values have been changed. I tried almost everything. I gave the new array a new name, tried using this-> to access the values and stored the array as a private element to be sure it can not be changed somehow. I think I miss something important.
I guess I am not sending the array, but only the address of the first element of the array. But still, when accessing the array at the location where I created the array, the values are correct.
It is better to show the problem with an example I have made. I am simply sending the array "keys" from object "Game" to object "Player" when initialising "Player Joyce". I store this array under the name "keyspressed". After initialising both "Game game" and "Player Joyce" I access the function "render()" continuously from a gameloop. I have printed the values of the array in the different constructors and functions.
In short, I would like that the values of "keyspressed" will always stay {1, 2, 3, 4, 5}.
I have edited my example and made a MCVE. I hope now someone can help me better:p
#include<stdio.h>
#include<vector>
class Player {
private:
int *keyspressed;
public:
Player(int keys[5]) {
keyspressed = keys;
printf("%i - %i - %i - %i - %i from when Player is constructed\n", keyspressed[0], keyspressed[1], keyspressed[2], keyspressed[3], keyspressed[4]);
}
void render() {
printf("%i - %i - %i - %i - %i from render() in Player\n", keyspressed[0], keyspressed[1], keyspressed[2], keyspressed[3], keyspressed[4]);
}
};
class Game {
private:
std::vector<Player> players;
int keys[5] = {1, 2, 3, 4, 5};
public:
Game() {
players.push_back(Player(keys));
printf("%i - %i - %i - %i - %i from when Game is constructed\n", keys[0], keys[1], keys[2], keys[3], keys[4]);
}
void render() {
//Render all players
for (int j = 0; j < players.size(); j++) {
players[0].render();
}
printf("%i - %i - %i - %i - %i from render() in Game\n", keys[0], keys[1], keys[2], keys[3], keys[4]);
}
};
class Window {
private:
std::vector<Game> games;
public:
Window() {
}
void loadGame() {
games.push_back(Game());
}
void render() {
//render all games
for (int i = 0; i < games.size(); i++) {
games[i].render();
}
}
};
class Program {
private:
std::vector<Window> windows;
public:
Program() {
//This program uses 1 window
Window window;
windows.push_back(window);
//load game
windows[0].loadGame();
run();
}
void run() {
//updates the renderer
for (int i = 0; i < windows.size(); i++) {
windows[i].render();
}
}
};
int main( int argc, char* args[]) {
Program program;
return 0;
};
Output:
1 - 2 - 3 - 4 - 5 from when Player is constructed
1 - 2 - 3 - 4 - 5 from when Game is constructed
237368672 - 32764 - 3 - 4 - 5 from render() in Player
1 - 2 - 3 - 4 - 5 from render() in Game