i'm doing a C++ project, a very simple video game. This game must have infinite levels, and every level has a random number of platforms. I created an object for platform, here the hpp:
class platform {
protected:
hitBox box;
public:
platform (int a, int b, int c, int d);
void print();
hitBox getHitbox();
};
and an object for the level, that has a list of platforms in it, because the numbers of platforms can change for every level, here the hpp:
struct Pplatform {
platform* plat;
Pplatform* next;
};
typedef Pplatform* lPlatform;
hitBox newRandomPlat (hitBox where);
class level {
protected:
int nlevel;
lPlatform platforms;
public:
level (int nl, bulletManager* bM);
void print_platforms ();
infoCrash check (hitBox ht, char d);
int lnumber ();
};
but in level.cpp i have and error of segmentation fault when I create a platform object in the list:
this->platforms->plat = new platform (0, 1, COLS, 0);
this line give me segmentation fault, i have tried to write it in different way like this:
platform plt = platform (0, 1, COLS, 0);
this->platforms->plat = &plt ;
but it doesn't work. Could u help me please? thank
The segmentation problem you are experiencing is most likely caused by accessing memory that was not properly allocated. You're attempting to set a value to this->platforms->plat
in your code, but it appears that you haven't allocated memory for this->platforms
.
You can try this revised code of your level constructor that uses the platform member:
level::level(int nl, bulletManager* bM) : nlevel(nl), platforms(nullptr) {
}
When you build a new platform, you must allocate memory for it dynamically and update the platforms list.