V
V
vladislaav2020-05-15 17:06:33
C++ / C#
vladislaav, 2020-05-15 17:06:33

Why don't the values ​​in the struct change?

I am writing the game "Sea Battle". When changing the value of ships.x or ships.y (from the structure), the value does not change (
Did I write the function correctly at all?

The code

struct Ships {
  int x = 1;
  int y = 1;
};

void CheckPressedKey(char** area, char** area_buf, int row, int col)
{
  struct Ships ships;
  int key, counter = 1;
  while (counter > 0)
  {
    key = _getch();
    switch (key)
    {
      case 77: //Вправо - D
      {
        if (ships.x + ships.number_decks - 1 < 9) ships.x += 1;
                                cout << ships.x; //Тут выводит верно )
        PrintShips(area, area_buf, row, col);

      } break;
    }
  }
}

void PrintShips(char** area, char** area_buf, int row, int col) {
  struct Ships ships;
  cout << ships.x; //Тут выводит 1 все время (
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-05-15
@vladislaav

void CheckPressedKey(char** area, char** area_buf, int row, int col)
{
  struct Ships ships;

The ships structure is automatic, exists on the stack only during the execution of this function, is created (with undefined field values) when entering it and disappears when exiting.
If you wanted it to persist between calls to this function, you should have added static: . This change will work as you intended, but having static variables in functions is not good practice. Usually the best solution is to pass such data to the function as a parameter, for example:static struct Ships ships;
void CheckPressedKey(char** area, char** area_buf, int row, int col, struct Ships *ships)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question