Reputation: 142
the code below has an error please help me how can I fix it. I'm beginner in 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....}
The error is: a value of type "void*" cannot be assigned to an entity of type "char*"
Upvotes: 2
Views: 438
Reputation: 368
it's clear as you see in error report! you should cast every thing at the other side of "=" operator to (char*)!
image=(char*)malloc(3*1450*900*sizeof(char));
Upvotes: 1
Reputation: 23610
The reason your code doesn't work is, that malloc()
returns a void*
which cannot be implicitly converted to a char*
. Therefore, it is said that malloc()
is not type-safe. You can cast the returned pointer explicitly by writing (char*)malloc(3*1450*900)
but this is kinda ugly. (BTW sizeof(char)
is always 1.)
In modern C++ you should do memory allocations using containers like std::vector<T>
. Also: try to avoid global variables outside functions and classes. Here's what I would write:
int main()
{
std::vector<char> image( 3*1450*900 ); // automatically fills with zeros.
}
This has the advantage, that memory management is done automatically. The allocated memory will be freed when the image
object is destroyed.
Upvotes: 4
Reputation: 11406
First, In C++ you should be using new / new[]
and delete / delete[]
instead of malloc()
.
An even better way would be to use std::vector
: std::vector<char> image(3*1450*900);
If you really would need to use malloc()
in C++, you need to cast the return value (malloc()
returns a void*
):
image = (char*)malloc(3*1450*900*sizeof(char));
And of course, always check the return value before continuing.
Upvotes: 5
Reputation: 1216
Since you're using C++, you should instead be creating your arrays with new[]
and deleting them with delete[]
.
int main(int argc, char **argv)
{
image = new char[3 * 1450 * 900];
// ... some code here? ...
// When you're finished with image:
delete[] image;
// ... some code here? ...
return 0;
}
You don't need sizeof
if you're using the new[]
or new
operators, but even so, I want to mention that sizeof(char)
is always equal to 1.
If you are using C++11 (you should be!), then it might be more appropriate to declare image as a unique_ptr<char[]>
to prevent memory leaks caused by improper exception handling or simply forgetting the delete[]
.
Upvotes: 2