簡體   English   中英

無法將二維數組分配給 c 中的結構

[英]can not assign a 2-d array to struct in c

我正在寫一個蛇游戲。 我有一個包含蛇數據的結構,例如蛇長度的snake.h等。這是蛇.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永遠不會顯示。 我得到分段錯誤。 我需要的是一個二維數組,其中包含蛇所在像素的地址,長度是蛇將占據的像素數。

我希望如果缺少詳細信息,請告訴我。

正如Weather Vane在評論中指出的那樣,您沒有考慮每個元素的大小。

這個 function 應該正確分配 memory :

#include <stdlib.h>

struct Snake *set_snake(int length_, int pos_[][2], int direction_)
{
    struct Snake *snake = malloc(sizeof *snake + sizeof(int[length_][2]));

    snake->length = length_;
    memcpy(snake->pos, pos_, sizeof(int[length_][2]));
    memcpy(snake->first_pos, pos_[length_-1], sizeof(int[2]));
    memcpy(snake->last_pos, pos_[0], sizeof(int[2]));
    snake->direction = direction_;

    return snake;
} 

像這樣調用 function:

struct Snake *snake;
snake = set_snake(1, pos, UP);

順便說一句,我在 C 中寫了一個貪吃蛇游戲時,我將每個元素的 x 和 y 坐標存儲在一個鏈表中,這很容易操作。 有興趣的可以看看我的實現

暫無
暫無

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

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