Pointers in C vs C ++

Possible duplicate:
Why does C ++ require a cast for malloc (), but C isn't?

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

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

Error in C ++ compilation:

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

Any idea what could be the reason?

+4
source share
3 answers

While in C you can use the / to void pointer to other types of pointers implicitly, it is not allowed in C ++, and you need to explicitly specify it:

 b = (int (*)[10])calloc(20, sizeof(int)); 
+6
source

C++ is a more stringent type checking language than C Thus, you need to output it manually, but in C it is automatically created automatically.

Here, calloc returns void* and b is of type int(*)[] , so typing is mandatory.

Other types of castes are also available in C ++, you need to keep in mind

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

See this for more details. When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used?

+1
source

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

0
source

Source: https://habr.com/ru/post/1444041/


All Articles