Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void pointer in function call in C++ vs C

I have this piece of code that works in C but not C++, is that any way to make it work on both C and C++ ?

void foo(void* b)
{
   int *c = b;
   printf("%d\n",*c); 

}

int main ()
{
 int a = 1000;

 foo(&a);
 return 0;
}

output:

C++:

1 In function 'void foo(void*)':
2 Line 3: error: invalid conversion from 'void*' to 'int*'
3 compilation terminated due to -Wfatal-errors.

C:

1000

Please help

like image 611
user1998844 Avatar asked Apr 03 '17 03:04

user1998844


2 Answers

invalid conversion from void* to int*

In order to make an conversion from void* to int* you will need to cast b as int* when assigning it to c. Do:

int *c = (int*) b;

This works in C++ and in C.

like image 131
BusyProgrammer Avatar answered Sep 21 '22 21:09

BusyProgrammer


C allows implicit conversion between void* and any pointer to object type, C++ does not. To make your code compatible with both languages, you could type foo( (void*)&a );.

However, using void pointers is discouraged in both languages - they should only be used as a last resort. If you want the function to be type-generic in C, you'd use the _Generic keyword. In C++ you'd use templates.

like image 45
Lundin Avatar answered Sep 18 '22 21:09

Lundin