簡體   English   中英

如何在 C 上的 function 中更改全局二維結構數組?

[英]How to change global two dimensional array of structs inside a function on C?

我想使用指針更改全局數組,但它似乎不起作用。 我希望有更有效的方法來完成這項工作。

這是一段代碼,當它到達一行時顯示分段錯誤異常->

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

#define MWIDTH  512
#define MHEIGHT 512

typedef struct
{
    int artifactValue;
    int artifactType;
    int occupation;
} sTile;

sTile *tile[MHEIGHT][MWIDTH];

FILE* f;
int height, width, ii, jj;
int array[MHEIGHT][MWIDTH];

void getDimensions()
{
    if ((f = fopen("C:\\C projects\\amazons\\state.txt", "r")) == NULL)
        exit(1);
    if (fscanf(f, "%d%d", &height, &width) != 2)
        exit(1);
    if (height < 1 || height > MHEIGHT || width < 1 || width > MWIDTH)
        exit(1);
}

void getBoard()
{
    for(jj=0; jj<height; jj++)
        for(ii=0; ii<width; ii++)
        {
            fscanf(f, "%d", &array[jj][ii]);

            if (array[jj][ii] < 10)
            {
                tile[jj][ii] -> artifactValue = 0;
                tile[jj][ii] -> artifactType = 0;
                tile[jj][ii] -> occupation = array[jj][ii];
            }

            else if (array[jj][ii] < 100)
            {
                tile[jj][ii] -> artifactValue = 0;
                tile[jj][ii] -> artifactType = array[jj][ii] / 10;
                tile[jj][ii] -> occupation = array[jj][ii] % 10;
            }

            else if (array[jj][ii] < 999)
            {
                tile[jj][ii] -> artifactValue = array[jj][ii] / 100;
                tile[jj][ii] -> artifactType = array[jj][ii] % 100 / 10;
                tile[jj][ii] -> occupation = array[jj][ii] % 100 % 10;
            }
        }
}
sTile *tile[MHEIGHT][MWIDTH];

這是指針的二維數組。 您需要為此數組中的每個指針分配 memory。

for(jj=0; jj<height; jj++)
    for(ii=0; ii<width; ii++)
    {
        fscanf(f, "%d", &array[jj][ii]);
        tile[jj][ii] = malloc(sizeof(sTile));
        ...
    }
}

當您不需要使用它們時,不要忘記釋放每個指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM