1

I'm trying to use calloc in my program. With an explicit cast it compiles and runs fine, but when I try to remove the explicit cast of malloc I see the following error:

Assigning to '... *' (aka '....... *') from incompatible type 'void *'

How can I compile my code without an explicit cast of calloc in Xcode?

Community
  • 1
  • 1
Mohan
  • 1,871
  • 21
  • 34
  • 2
    Are you sure you are compiling as C code and not C++? Or perhaps objective-C (which I know nothing about)? C and C++ are distinctly different languages with different casting requirements. If so, please fix up your tags. – kaylum Nov 18 '15 at 05:33

1 Answers1

3

You are attempting to compile your C code as C++.

While it is true that some C code is also valid in C++, you have come across an example of C code that isn't valid in C++.

That is, C++ does not offer the implicit conversions to/from void * that C does.


You should always compile your C code using a C compiler, for the following three reasons:

  • You don't need to compile C code using a C++ compiler.
  • You're missing out on the best parts of C++.
  • You're missing out on the best parts of C.

The only reason people try to compile C code with a C++ compiler is that they anticipate using their C code in a C++ project. However, this is unnecessary because you can usually compile your C code using a C compiler, compile your C++ code using a C++ compiler and then link the two together. For example:

gcc -c c_code.c
g++ -c cpp_code.cpp
gcc cpp_library.o c_library.o

In C++, it is generally a bad idea to use *alloc functions. Those who program specifically in C++ will usually cringe at *alloc use.


In C, it is always a bad idea to explicitly cast void *, as the link you provided explains. Those who program specifically in C will cringe at unnecessary boilerplate that potentially introduces bugs.

Community
  • 1
  • 1
autistic
  • 1
  • 3
  • 35
  • 80