我想出了一个学习 C 的项目,但我有点碰壁了。 该项目只是一个纸牌游戏,玩家有两套纸牌,一套是一组固定大小的纸牌,另一套是他们的纸牌集合,可以根据需要大小。 卡片结构如下:
struct card {
char name[256];
char special[256];
char type[100];
char rarity[100];
int points;
};
然后我有一个名为 coll.txt 的集合文件
first card goes here 50
second card goes here 70
...
然后我有一个(草率的)函数从文件中读取并将其存储到临时卡中:
void read_into_collection(FILE *f) {
char *file_text;
char *token;
int i;
struct card temp;
file_text = (char *) malloc(sizeof(struct card));
while(fgets(file_text, sizeof(struct card), f)) {
for(i = 1, token = strtok(file_text, " "); token; i++, token = strtok(NULL, " ")) {
switch (i) {
case 1:
strcpy(temp.name, token);
break;
case 2:
strcpy(temp.special, token);
break;
case 3:
strcpy(temp.type, token);
break;
case 4:
strcpy(temp.rarity, token);
break;
case 5:
temp.points = atoi(token);
break;
default:
i = 0;
break;
}
}
}
free(file_text);
}
所以到了i = 6
的时候,我已经准备好将临时卡移动到集合中,并将下一张卡读入临时变量,依此类推。但我该怎么做呢?我很难弄清楚集合实际上应该是什么。一开始我以为:
struct card *collection = (struct card *) malloc(number_of_cards * sizeof(struct card));
但是,如果我是正确的,malloc()
返回一个指向内存块的指针,并且内存不像数组那样是连续的,因此我无法增加指针来存储卡片。
我还尝试计算文件中的行数(每行都是一张卡片),然后创建一个该大小的数组,但出现错误,表明该值不是恒定的。
将这些卡片存储为集合的最佳方法是什么?我只想让集合成为一个非常大的数组,但我觉得这种情况在项目中经常出现,我宁愿学习如何处理它,而不是采取简单的方法。
最佳答案
But, if I am correct, malloc() returns a pointer to a chunk of memory and the memory is not sequential like an array, so I cannot increment the pointer to store cards.
错误。它是顺序的。您可以使用 malloc()
创建任何内容的数组:
mystruct* ptr = (mystruct*) malloc(sizeof(mystruct) * numberOfStructs)
for(int i = 0; i < numberOfStructs, i++) {
ptr[i].setSomeInfo(x);
}
这是用 C 语言执行此操作的标准方法。
关于c - 如何存储从 C 语言文件中读取的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11020275/