我在从文件加载数据时遇到问题。 这段代码用一些随机数据填充高分(仅用于调试)
int i = 0;
for (i = 0; i < MAX_HIGH_SCORE; i++)
{
high_score_name[i] = al_ustr_new("123456789012345678901");
high_score[i] = 1000*i;
}
之后我将所有这些保存到文件中。
ALLEGRO_FILE* high_score_file = al_fopen("hs.txt","wb");
for (i = 0; i < MAX_HIGH_SCORE; i++)
{
int buffer = al_ustr_size(high_score_name[i]);
al_fwrite32le(high_score_file, buffer);
al_fwrite(high_score_file, al_cstr(high_score_name[i]), buffer);
al_fwrite(high_score_file, &high_score[i], sizeof(high_score[i]));
}
al_fclose(high_score_file);
它运作得很好。它有四个字节为大小保留,然后是high_score_name[]
的21个字符,后跟high_score[]
int,也占用4个字节。
当我尝试加载时出现问题。我试图在很多方面做,但它不会编译,因为行
char* buffer= al_malloc(size);
给出错误:
类型“void *”的值不能用于初始化“char *
类型的实体
for (i = 0; i < MAX_HIGH_SCORE; i++)
{
int size = al_fread32le(high_score_file);
char* buffer = al_malloc(size);
al_fread(high_score_file, buffer, size);
high_score_name[i] = al_ustr_new_from_buffer(buffer, size);
int *buffer2 = &high_score[i];
al_fread(high_score_file, buffer2, sizeof(high_score[i]));
al_free(buffer);
}
al_fclose(high_score_file);
我坚持了两天,我真的会帮助你。
答案 0 :(得分:0)
malloc的输出类型为void *,你应该尝试显式地转换为char *。
char* buffer = static_cast<char *>(al_malloc(size))
答案 1 :(得分:0)
如果你的函数在内部使用malloc来分配内存,那么malloc返回一个void *,如果你的al_malloc返回void * ...使用类型转换为conert将它转换为char *。
char * buffer =(char *)al_malloc(size);
这应该有用。
malloc的函数原型:
void *malloc(size_t size);