error: a value of type "void *" cannot be assigned to an entity of type "float *"

StackOverflow https://stackoverflow.com/questions/17415965

  •  02-06-2022
  •  | 
  •  

Pergunta

Any idea why is this happening here?

float *image;
long size_img=par->N*par->M;

image = calloc(size_img, sizeof(float));//the compiler shows error here

The error is

error: a value of type "void *" cannot be assigned to an entity of type "float *"

Should I do a cast? The bogus thing is that I do the same elsewhere on the program and that error is not shown.

I have this as part of a struct I named par

long *tbegin;

and then I do

par->tbegin = calloc( SUMA_J, sizeof ( long ) );

And I get no error.

Foi útil?

Solução

What is happening here is that most likely you are inadvertently compiling your code as C++ code. In C++ (as opposed to C) void * is not implicitly convertible to other pointer types.

It you intend to write your code in C, make sure you compile it as C. It you intend to write your code in C++, you will have to use explicit type conversion operators to convert void * pointers to other pointer types.

The conversion to long * pointer type probably happens in other translation unit (i.e. other file), which is compiled as C. That is probably why it succeeds.

Note that compilers can use C and C++ mode independently for each translation unit. Many compilers will choose between C and C++ based on file extension, compiling .c files as C and .cpp files as C++.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top