C code with malloc doesn't compile!

Started by
5 comments, last by Zahlman 19 years, 8 months ago
Hello, in the following code, the compiler returns the message: "invalid conversion from `void*' to `int*' " and the code doesn't compile!

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int *p;
  p = malloc(40 * sizeof(int));

...

So, I have tried this: p = (int)malloc(40 * sizeof(int)); and it doesn't compile too! What's wrong?
Alfred Reinold Baudisch[Game Development Student] [MAC lover] [Ruby, Ruby on Rails and PHP developer] [Twitter]
Advertisement
int* p = (int*)malloc(40 * sizeof(int));

You were trying to cast a pointer into an int.
Oh.. I didn't know it. Thanks evolutional, it works now.
Alfred Reinold Baudisch[Game Development Student] [MAC lover] [Ruby, Ruby on Rails and PHP developer] [Twitter]
o_O

My understanding is that you're not supposed to need to cast returns from malloc() any more, and that in fact you shouldn't for "good style" any more (because it will "hide the error of not including stdlib.h"; I don't know the details there though).

How old is your compiler?
The reason is that you're compiling legal C code in a C++ compiler.
Quote:Original post by Zahlman
o_O

My understanding is that you're not supposed to need to cast returns from malloc() any more, and that in fact you shouldn't for "good style" any more (because it will "hide the error of not including stdlib.h"; I don't know the details there though).

How old is your compiler?


Zahlman, I'm using the new version of DevC++ (4.9.9.0) that comes with newer mingw.
Alfred Reinold Baudisch[Game Development Student] [MAC lover] [Ruby, Ruby on Rails and PHP developer] [Twitter]
Aha. fallenang3l is right then. Use an actual C compiler for C code if you can; try not to be messing around with malloc() and free() in a C++ environment. Bad mojo.

This topic is closed to new replies.

Advertisement