繁体   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