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

Viewed 78

I'm writing a snake game. I have a structure which contains data of the snake, such as position of snake length etc. This is the snake.h file:

#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_           ;
}

and in the 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;
}

and in 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

The problem is that it can not do memcpy in set_snake. The hello will never be shown. I get segmentation fault. The thing I need is a 2 dimensional array which contains address of the pixel which snake is in, and the length is the number of pixels the snake would occupy.

I hope if there is lack of detail, let me know it.

1 Answers

As Weather Vane pointed out in the comments, you are not taking the size of each element into account.

This function should allocate memory correctly:

#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;
} 

Call the function like this:

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

By the way, when I wrote a Snake game in C, I stored the x- and y-coordinate of each element in a linked list, which is very easy to manipulate. If you are interested, you can have a look at my implementation.

Related