Search code examples
c++allegro5

error creating buffer to load data


I have a problem with loading data from file. This piece of code fills high scores with some random data (its just for debug)

int i = 0; 
for (i = 0; i < MAX_HIGH_SCORE; i++)
{
    high_score_name[i] = al_ustr_new("123456789012345678901");
    high_score[i] = 1000*i;
}

after that i save all of that to file.

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);

It work just fine. It have four bytes reserved for size then 21 characters of high_score_name[] followed by high_score[] int which takes also 4 bytes.

Problem starts when i try to load it up. I tried to do in many ways but it won`t compile because line

char* buffer= al_malloc(size); gives error :

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);

Im stuck with it for two days and i would really apreciate any help.


Solution

  • The output of malloc has type void* which you should try explicitly casting to char* .

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