Как заменить 1 значение массива при индексе в C - PullRequest
0 голосов
/ 03 мая 2020

Я пытаюсь создать игру тральщика. Чтобы показать, что флаг установлен в этой позиции, я хочу поставить 4 в этот слот. Я не совсем уверен, как обновить 1 элемент массива, и вся информация, которую я нашел в сети, зациклена на всем массиве и изменила значения. Есть какой-либо способ сделать это? У меня проблема с c строкой:

(*arr)[tempH][tempV] = 4;

Остальное здесь.

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <time.h>

int * arr;
void initialization(int vf, int hf) {

  printf("%s\n", "Setting up the game");

  int i, j, count = 0; // fills the board with a random sequence of 1's and 0's
  for (i = 0; i < hf; i++) //representing bombs and empty spaces
    for (j = 0; j < vf; j++)
      *
      (arr + i * vf + j) = (rand() % 2);
  //0 is nothing 1 is bombs
  for (i = 0; i < hf; i++) {
    for (j = 0; j < vf; j++) {
      printf("%d ", *(arr + i * vf + j));
      if (j == hf - 1) {
        printf("\n"); //creates new line at the end of row
      }
    }
  }
  printf("%s\n", "1 contains a bomb, 0 does not."); //game setup
}

void teardown() {
  printf("%s\n", "Destroying the game"); //game destroy
}

void input(char select, char * command, int * coord_h, int * coord_v, int * stop) {
  const int tempH = * coord_h; //creates temporary holders for coords
  const int tempV = * coord_v;

  printf("%s\n", "[F]Flag ");
  printf("%s\n", "[R]Remove Flag ");
  printf("%s\n", "[A] Assert a spot is mine free ");
  printf("%s\n", "[Q] Quit");
  scanf(" %c", & select);

  if (select == 'f') {
    printf("Please enter a horizontal coordinate: "); //selects a coordinate
    scanf(" %d", coord_h);
    printf("Please enter a vertical coordinate: "); //selects a coordinate
    scanf(" %d", coord_v); &
    (*arr)[tempH][tempV] = 4;

    //TODO: REST OF LETTERS
  } else if (select == 'r') {

  } else if (select == 'a') {
    printf("Please enter a horizontal coordinate: "); //selects a coordinate
    scanf(" %d", coord_h);
    printf("Please enter a vertical coordinate: "); //selects a coordinate
    scanf(" %d", coord_v);
  } else if (select == 'q') {
    * stop = 1; //Stops loop in main
  } else {

  }
}

void update(int * coord_h, int * coord_v, int * type, int ** ptr, int hf, int vf) {
  const int tempH = * coord_h; //creates temporary holders for coords
  const int tempV = * coord_v;

  printf("%d\n", ptr[tempH][tempV]); //testing values
  if (ptr[tempH][tempV] == 1) { //checks to see if array at that point is a bomb
    * type = 1; //returns type for display (bomb)

  } else {
    * type = 0; //returns type for display(not bomb)
  }

  int i, j, count = 0; // fills the board with a random sequence of 1's and 0's
  for (i = 0; i < vf; i++) { //representing bombs and empty spaces

    //memcpy(&updateArr[i], &arr[i], sizeof(int));

  }
  for (i = 0; i < hf; i++) {
    for (j = 0; j < vf; j++) {
      printf("%d ", *(arr + i * vf + j));
      if (j == hf - 1) {
        printf("\n"); //creates new line at the end of row
      }
    }
  }
}

void display(int * type, int ** ptr, int hf, int vf) {

  if ( * type == 1) { //takes type from update and displays
    printf("%s\n", "BOOM");

  } else if ( * type == 0) {
    printf("%s\n", "OK");
  }

}

int main() {
  srand(time(NULL)); //creates random seed for bomb placement
  int * stop = 0;
  char select;
  int * displayType;
  char command[100];
  int v, h; //board sizing
  int coord_h, coord_v; //user inputed coords

  printf("%s\n", "Enter horizontal board length: ");
  scanf("%d", & h);
  printf("%s\n", "Enter vertical board length:");
  scanf("%d", & v);
  const int vf = v,
    hf = h; //sets constants for board so the array can use them
  arr = (int * ) malloc(hf * vf * sizeof(int)); //dynamic memory allocation for board 2d array
  int ** ptr = & arr;

  initialization(vf, hf);
  while (stop == 0) {
    input(select, command, & coord_h, & coord_v, stop);
    update( & coord_h, & coord_v, displayType, ptr, hf, vf);

    display(displayType, ptr, hf, vf);

  }
  teardown();
}

1 Ответ

1 голос
/ 03 мая 2020

Проблема в том, что вы инициализируете arr как одномерный массив и хотите получить к нему доступ, как к его 2D. В основном arr - это просто указатель на первый индекс переменных hf * vf int, которые непрерывны в памяти. Если вам нужен фактический 2D-массив, вам нужно изменить arr на указатель на указатель (int **), тогда вы можете получить к нему доступ, например arr[i][j]. В качестве альтернативы, вы можете сохранить это как (массив 1D) и реализовать функцию, которая получает arr, i, j и новое значение в качестве параметров, затем обновляет *(arr + i * vf + j).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...