我正在编写一款贪吃蛇游戏。我有一个包含蛇的数据结构,例如蛇的位置和长度等。这是snake.h
文件:
#ifndef SNAKE_HEAEDER
#define SNAKE_HEAEDER
#include "direction.h"
#include <string.h>
struct Snake {
int length;
int* pos[2];
int first_pos[2];
int last_pos[2];
int direction;
};
void set_snake(struct Snake *snake, int length_, int pos_[][2], int direction_){
snake->length = length_ ;
memcpy(snake->pos, pos_, length_) ;
printf("hello\n");
memcpy(snake->first_pos, pos_[length_-1],1) ;
memcpy(snake->last_pos, pos_[0],1) ;
snake->direction = direction_ ;
}
并且在 main.c
文件中:
#include <stdio.h>
#include "snake.h"
int main(){
struct Snake *snake;
int pos[2][2] = {{1,2}};
set_snake(snake,1,pos,UP);
return 0;
}
在 direction.h
中:
#ifndef DIRECTIONS_HEADER
#define DIRECTIONS_HEADER
#define UP 0
#define DOWN 1
#define RIGHT 2
#define LEFT 3
#define CURRENT_DIRECTION(x) (x.direction)
#endif
问题在于它不能在
set_snake
中执行 memcpy
,hello
将永远不会被显示。我得到了分段错误。我需要的是一个二维数组,其中包含蛇所在像素的地址,长度为蛇占用的像素数。希望如果缺少细节,请让我知道。
struct Snake *snake = malloc(sizeof *snake);
- Andy Sukowski-Bangstruct Snake snake;
- 001memcpy()
调用中,您没有考虑每个元素的大小。一个int
大于 1 个字节。 - Weather Vane