我正在尝试使用 SDL 用 C 编写一个小程序,显示一个在网格上移动的机器人。此网格由 0 和 1 的 txt 文件表示。
这是从 txt 文件创建数组的函数,它有效。
// create a map(array) from a text file
int (*newMap())[SIZE_HEIGHT][SIZE_WIDTH]
{
static const char filename[] = "input.txt"; /* the name of a file to open */
FILE *file = fopen(filename, "r"); /* try to open the file */
int map[SIZE_HEIGHT][SIZE_WIDTH];
char line[BUFSIZ]; /* space to read a line into */
int k = 0;
while ( fgets(line, sizeof line, file)!=NULL && k<SIZE_HEIGHT) /* read each line */
{
int i;
char *token = line; /* point to the beginning of the line */
for ( i = 0; i<SIZE_WIDTH; i++ )
{
map[k][i]=((int)*token)-48;
token+=sizeof(char);
printf("map[%d][%d]=%d\n", (int)k,(int)i,map[k][i]);
}
puts("----\n");
k++;
}
fclose(file);
int (*p)[SIZE_HEIGHT][SIZE_WIDTH];
p=↦
return p;
然后我尝试将网格放在屏幕上(不是整个功能):
#include <stdlib.h>
#include <stdio.h>
#include <SDL/SDL.h>
#include <time.h>
#include <string.h>
#include "Parameters.h"
#include "simulation.h"
#include "editor.h"
void simulate(SDL_Surface *ecran)
{
SDL_Surface *carreVert = SDL_LoadBMP("carreVert.bmp");
SDL_Surface *carreRouge = SDL_LoadBMP("carreRouge.bmp");
SDL_Surface *robot = SDL_LoadBMP("robotRouge.bmp");
SDL_SetColorKey(robot, SDL_SRCCOLORKEY, SDL_MapRGB(robot->format, 255, 255, 255));
int (*map)[SIZE_HEIGHT][SIZE_WIDTH];
map=newMap();
SDL_Rect positionFond;
int i;
int j;
for(j=0; j<SIZE_HEIGHT; j++)
{
for(i=0; i<SIZE_WIDTH; i++)
{
positionFond.x = 100*i;
positionFond.y = 100*j;
if((*map)[j][i]+1)
{
SDL_BlitSurface(carreVert, NULL, ecran, &positionFond);
}else
{
SDL_BlitSurface(carreRouge, NULL, ecran, &positionFond);
}
}
}
然后奇怪的事情发生了:当我用调试器观察数组 *map 时,我发现在我进行测试时值正在改变。所以网格确实出现了,但没有正确的模式。为什么会这样?
编辑:编译器没有错误。
编辑:我们很乐意接受任何关于可能会做什么的猜测。
最佳答案
数组 map
是函数的本地数组。当函数结束时,它就不复存在了。您将它的地址传递给调用者,但是当调用者尝试使用它时……砰!
快速解决方案:使数组 map
成为一个static
:确保每次运行都不会多次调用 newMap
.
其他解决方案:
- 向外移动数组的创建并传递地址
- 使用
malloc
和 friend 来管理数组
关于c - 数组的值在执行期间随机变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7774617/