我如何创建一个可以在 C 代码的其他部分使用的结构体数组?

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

我必须在 C 中创建一个结构矩阵,通过一个只能以维度作为参数的 void 函数,但是我不能在 main 或其他函数中使用它。

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

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){
    struct 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;
        }
    }
}

但是当我尝试时

printf(tablero[1][1].vida);
在 main() 中它说
error: request for member ‘vida’ in something not a structure or union
。 我如何更改函数以便以后可以重用和修改矩阵?

提前谢谢您<3.

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

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

#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.