如何在分配内存时修复此错误?

amI*_*ist 2 c++ malloc casting

下面的代码有错误,请帮助我如何解决它.我是C++的初学者.

int main(int    argc,   char    **argv)
{
image=malloc(3*1450*900*sizeof(char));      /*  to  ALLOCATE    MEMORY  required    to  SAVE    the file    */
    some thing else....}
Run Code Online (Sandbox Code Playgroud)

错误是:类型"void*"的值不能分配给"char*"类型的实体

Dan*_*_ds 5

首先,在C++中你应该使用new / new[]delete / delete[]不是malloc().

更好的方法是使用std::vector:std::vector<char> image(3*1450*900);


如果你真的需要malloc()在C++中使用,你需要转换返回值(malloc()返回一个void*):

image = (char*)malloc(3*1450*900*sizeof(char));
Run Code Online (Sandbox Code Playgroud)

当然,在继续之前总是检查返回值.