如何在堆内存中创建结构体数组并在 C 中的其他函数中使用它? [已关闭]

问题描述 投票:0回答:1

感谢评论的人<3, let me explain better. I have to create a Battleship like game but with a matrix of Struct named Dirt that have HP (1-3) and a 5% chance of having a treasure under it (1 or 0).

所以这个程序的目的是让我理解指针和堆内存,目前我的函数甚至没有使用堆。 创建棋盘功能的条件是:

  • 它必须是一个 Void 函数,只能接收一个参数,即放置泥土和宝藏的矩阵的维度。

  • 我可以修改和访问棋盘,例如,爆炸炸弹以揭示泥土下的宝藏或删除棋盘。

这是我创建结构矩阵的函数...

const int chance[5]={1,2,3,4,5};


typedef struct Tierra{
    int vida; // 1-3 random health points
    int es_tesoro; // 1 or 0 , 5% chance of having a treasure under
} Tierra;

void IniciarTablero(int n){
    Tierra tablero[n][n];
    for (int i=0 ; i<n ; i++){
        for (int j=0 ; j<n ; j++){
            tablero[i][j].vida = (rand() % 3) + 1; // 1-3 random health
            int probabilidad = (rand() % 100);
            int contenido = 0;
            for (int c=0 ; c<5 ; c++){ //check 5% chance
                if(probabilidad==chance[c]){
                    contenido = 1;
                }
            }
            tablero[i][j].es_tesoro = contenido;
        }
    }
}

当然,现在我无法访问该板,因为我无法归还它,那么我如何更改我的函数以使用堆内存并能够稍后删除并释放该内存。

非常感谢<3.

arrays c matrix struct void
1个回答
-1
投票

这似乎是范围问题。他们可以通过多种方式来实现这一目标,我尝试过的一种方式如下所述。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

const int chance[5] = {1, 2, 3, 4, 5};

typedef struct Tierra {
    int vida;      
    int es_tesoro; 
} Tierra;

void IniciarTablero(Tierra tablero[][5], int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            tablero[i][j].vida = (rand() % 3) + 1; 
            int probabilidad = rand() % 100;
            int contenido = 0;
            for (int c = 0; c < 5; c++) { 
                if (probabilidad == chance[c]) {
                    contenido = 1;
                }
            }
            tablero[i][j].es_tesoro = contenido;
        }
    }
}

int main() {
    srand(time(NULL)); 

    int n = 5; 
    Tierra tablero[n][n];

    IniciarTablero(tablero, n);

    printf("Vida of cell [1][1]: %d\n", tablero[1][1].vida);

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.