[英]How to change global two dimensional array of structs inside a function on C?
I wanted to change a global array using pointers, but it doesn't seem to work.我想使用指针更改全局数组,但它似乎不起作用。 I would appreciate more effective ways to make the job done.
我希望有更有效的方法来完成这项工作。
Here is a piece of code, it shows Segmentation fault exception when it reaches a line with ->
这是一段代码,当它到达一行时显示分段错误异常
->
#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];
This is 2D array of pointers.这是指针的二维数组。 You need to allocate the memory for each pointer in this array.
您需要为此数组中的每个指针分配 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));
...
}
}
Do not forget to free each pointer when you do not need to use them.当您不需要使用它们时,不要忘记释放每个指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.