在c中从结构到结构的副本

问题描述 投票:0回答:1

你好,我想创建一个函数,该函数在内存中分配新结构,而不仅仅是指向旧结构结构

typedef enum {
    CLOSED,
    OPEN,
    MARKED
} TileState;

typedef struct {
    bool is_mine;                /* Records if mine is on the Tile */
    TileState tile_state;        /* Enum for status of the Tile state */
    int value;                   /* Number of neighbour tiles where is mine on; -1 if mine is not on */
} Tile;


typedef struct {
    int row_count;                                  /* Number of rows in the Board */
    int column_count;                               /* Number of columns in the Board */
    int mine_count;                                 /* Number of mines in the Board */
    Tile *tiles[MAX_ROW_COUNT][MAX_COLUMN_COUNT];   /* 2-dimensional struct array of the tiles */
} Board;

复制功能] >>

Board* copyboard(Board *board) {
 // copy from old board to new one the full information with allocating 
again it in the memory

    Board *newboard = malloc(sizeof(*board));    
    size_t size =sizeof(*(board->tiles)) * board->column_count * board->row_count;

    newboard->tiles = malloc(size);
    memcpy(newboard->tiles, game->board->tiles, size);
  // i tried something like this but its not finished


  free(board); /* i know that its not enought just i wanted to clear that this will be deleted */


  return newboard;


}

我想将旧信息保存在内存中的新位置上

你好,我想创建一个在内存中分配新结构的函数,不仅指向旧的结构typedef枚举{CLOSED,OPEN,MARKED} TileState; typedef ...

c memory copy structure
1个回答
0
投票

您必须为此使用malloc(),一旦不再需要返回值,别忘了将返回值free()

© www.soinside.com 2019 - 2024. All rights reserved.