正如@pridy所评论的,你不应该使用
void *
作为指针类型
在这种情况下。此外,你
不
为每个对象分配内存
实体
struct Tierra
.
请你试试:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct Tierra {
int vida; // random health (1-3)
int es_tesoro; // 1 or 0 (5% chance of having a treasure)
} Tierra;
Tierra ***tablero;
int dimension;
const int chance[5] = {1, 2, 3, 4, 5};
void IniciarTablero(int n)
{
tablero = malloc(n * sizeof(Tierra ***));
for (int i = 0; i < n; i++) {
tablero[i] = malloc(n * sizeof(Tierra **));
for (int j = 0; j < n; j++) {
Tierra *tierra = malloc(sizeof(Tierra)); // missing in the original code
tierra->vida = (rand() % 3) + 1;
int probabilidad = (rand() % 100);
int contenido = 0;
for (int c = 0; c < 5; c++) {
if (probabilidad == chance[c]) {
contenido = 1;
}
}
tierra->es_tesoro = contenido;
tablero[i][j] = tierra;
}
}
}
void MostrarTablero()
{
for (int i = 0; i < dimension; i++) {
for (int j = 0; j < dimension; j++) {
Tierra *imprimir = tablero[i][j];
printf("%d | ", imprimir->vida);
}
printf("\n");
}
}
int main()
{
dimension = 4; // just for example
IniciarTablero(dimension);
MostrarTablero();
// don't forget to free() memory after use
return 0;
}
请注意,检查返回值时省略了它
malloc()
只是
为了简单起见,专注于要点。
Btw如果值
dimension
是固定的(不是动态分配的),
最好使用简单的二维阵列
结构体Tierra
.