创建缓冲区以加载数据时出错

error creating buffer to load data

我在从文件加载数据时遇到问题。 这段代码用一些随机数据填充高分(仅用于调试)

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); 给出错误:

a value of type "void *" cannot be used to initialize an entity of type "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);

我坚持了两天,非常感谢任何帮助。

malloc 的输出类型为 void*,您应该尝试将其显式转换为 char*。

char* buffer = static_cast<char *>(al_malloc(size))

如果您的函数在内部使用 malloc 分配内存,则 malloc returns a void* 如果您的 al_malloc returns void*...使用类型转换将其转换为字符*.

char* 缓冲区 = (char*)al_malloc(大小);

这应该有效。

malloc函数原型:

  void *malloc(size_t size);