5

Possible Duplicate:
Why does C++ require a cast for malloc() but C doesn’t?

This particular piece of code runs fine in C, but gives compilation error when compiled as a C++ program.

#include<stdio.h>
#include<stdlib.h>
int main(){
    int (*b)[10];
    b = calloc(20, sizeof(int));
    return 0;
}

The error in C++ compilation is:

test.cpp: In function ‘int main()’:
test.cpp:9:28: error: invalid conversion from ‘void*’ to ‘int (*)[10]’ [-fpermissive]

Any idea what might be the reason?

Community
  • 1
  • 1
Abhinav Jain
  • 153
  • 2
  • 7

3 Answers3

7

While in C you may cast from/to void pointer to other pointer types implicitly, it is not allowed in c++, and you need to cast it explicitly:

b = (int (*)[10])calloc(20, sizeof(int));
MByD
  • 135,866
  • 28
  • 264
  • 277
1

C++ is more strict type checking language than C. So, you need to typecast it manually but in C it's typecasted automatically.

Here calloc returns void* and b is of type int(*)[] hence typecasting is mandatory.

In C++ other type castes are also available you need to keep in mind

<static_cast>
<const_cast>
<reinterpret_cast>
<dynamic_cast>

For more see this When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

Community
  • 1
  • 1
Omkant
  • 9,018
  • 8
  • 39
  • 59
0

C is more permissive when it comes to casting, C++ requires you to be explicit when casting. You should be casting it in the C version as well.

Casper Beyer
  • 2,203
  • 2
  • 22
  • 35
  • 4
    Actually, in C, the cast is generally regarded as a bad idea since it is verbose and can hide errors. See http://stackoverflow.com/q/605845/485561 – Mankarse Nov 05 '12 at 05:53