簡體   English   中英

從文件中讀取 c 中的結構數組中的 dma 結構時,如何分配 memory

[英]How do you allocate memory when reading from a file for a dma struct in a struct array in c

所以我有一個 map 它由一個結構數組組成,看起來像這樣


//Header files
#include <string.h>
#include <stdlib.h>
#include <dirent.h>

//Symbolic names
#define mapSize 301

//This struct will be used to store item data in the map
struct mapItem
{
    char name[21];
    short id;
    short type;
    short amount;
}; //End mapItem

//This struct will be used for map generation and storage
struct tile
{
    char name[21];
    short id;
    char description[100];
    short itemAmount;
    struct mapItem *item;
}; //End tile struct

//This struct variable is the map
struct tile map[mapSize][mapSize];

//Function signatures
void itemGen();

int main()
{
    
    char str[4];
    FILE *characterF, *inventoryF, *mapF;

    itemGen();

    //Opens map file
    /*Example file path is C:\*/
    strcpy(str, "C:\");
    mapF = fopen(str, "w");

    //writes map to file
    fwrite(map, sizeof(struct tile), (mapSize*mapSize), mapF);

    //Closes file
    fclose(mapF);

    /*This would not usually be streight after the file had been written to
    //Opens file
    mapF = fopen(str, "w");

    

    //Reads from file
    fread(map, sizeof(struct tile), mapSize*mapSize, mapF);

    return 0;
} //End main


/*This is just an example in the actual program the itemAmount is not always 3*/
void itemGen()
{

    short x, y;
    x = y  = 100;

    //Sets value of itemAmount for example
    map[y][x].itemAmount = 3;

    //Allocates 3 structs in memory
    map[y][x].item = (struct mapItem *)calloc(map[y][x].itemAmount, sizeof(struct mapItem));

    //This will add 3 items to the tile
    strcpy((map[y][x].item+0)->name, "Apple");
    strcpy((map[y][x].item+1)->name, "Bag");
strcpy((map[y][x].item+1)->name, "Bag");

} //End itemGen

一旦我開始閱讀文件部分,似乎我需要為將存儲在圖塊中的項目聲明 memory。 因為這不是我在代碼中提到的設定數字,所以我將如何 go 關於這個?

歡迎使用此過程的任何替代方法。 謝謝!

map數據寫入文件時需要序列化,從文件讀回時需要反序列化。 一種方法是:

for (int y = 0; y < mapSize; y++) {
    for (int x = 0; x < mapSize; y++) {
        fwrite(&map[y][x], offsetof(struct tile, item), 1, mapF);
        fwrite(map[y][x].item, sizeof(struct mapItem), map[y][x].itemAmount, mapF);
    }
}

為清楚起見,省略了錯誤檢查。

讀取類似於寫入,但需要分配 memory:

for (int y = 0; y < mapSize; y++) {
    for (int x = 0; x < mapSize; y++) {
        fread(&map[y][x], offsetof(struct tile, item), 1, mapF);
        map[y][x].item = calloc(map[y][x].itemAmount, sizeof(struct mapItem));
        fread(map[y][x].item, sizeof(struct mapItem), map[y][x].itemAmount, mapF);
    }
}

同樣,為了清楚起見,省略了錯誤檢查。

暫無
暫無

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

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