运行 我的代码无法修复此错误

Can't fix this error when running my code

我在尝试 运行 我的代码时遇到此错误:

“错误:从‘void*’到‘int*’的无效转换[-fpermissive] 9 | int *a = GC::allocate(sizeof(int));

我正在尝试创建一个充当垃圾收集器的函数,现在我首先尝试为指针进行动态分配(因为指针将指向它们各自的 chunk/block 内存,从 GC class).

分配

main.cpp:

int *a = GC::allocate(sizeof(int));
*a = 5;
cout << a << " " << *a << endl;

GC.cc:

void* GC::allocate(size_t size)
{
    Chunk();
    bool flag = 1;
    size_t i, j, l;
    for(i = 0; i < SHEET_SIZE; i++)
    {
        if(sheets2[i] == 0)
        {
            for(j = i; j < i+size; j++)
            {
                if(sheets2[j] != 0)
                {
                    flag = 0;
                    break;
                }
            }
            if(flag)
            {
                for(l = i;l < j;l++)
                {
                    sheets2[l] = 1;
                }
                chunk = &sheet[i];
                chunks.push_back(Chunk(chunk, size, 1));
                chunks_count++;
                return chunk;
            }
        }
    }
    return (char*)"ERROR";
}

您可以显式转换 return 值:

int *a = (int*) GC::allocate(sizeof(int));