0

I'm currently making a spaghetti mess that I call snake game and I ran into a problem. I defineda struct snakeSeg and below a head pointer, now the problem is at the initialisation not at declaring the pointer within itself. Take a look: '''

struct snakeSeg
{
    int snakeX;
    int snakeY;
    snakeSeg *next;
};

    snakeSeg *head = new snakeSeg;
    head->next = NULL;  //<-----Here's the problem that I ran into
    head->snakeX = 15;
    head->snakeY = 15;

''' If anybody had any idea what's wrong I'd love to read your input. Cheers!

1 Answers1

0

It looks like your code was outside of main.

struct snakeSeg
{
    int snakeX;
    int snakeY;
    snakeSeg *next;
};

int main()
{
    snakeSeg *head = new snakeSeg;
    head->next = nullptr; // it is better to use nullptr
    head->snakeX = 15;
    head->snakeY = 15;


    delete head; // also you need to free the memory
    return 0;
}

You can have it as a global variable like this:

struct snakeSeg
{
    int snakeX;
    int snakeY;
    snakeSeg *next;
};

snakeSeg *head = new snakeSeg; // all the rest of the code needs to be in a function

Another way to do this is the way @StoryTeller suggested in the comments:

struct snakeSeg
{
    int snakeX;
    int snakeY;
    snakeSeg *next;
};

snakeSeg *head = new snakeSeg{15, 15, nullptr};
bhristov
  • 3,137
  • 2
  • 10
  • 26