我有一段代码可以在 C 中运行,但不能在 C++ 中运行,是否有任何方法可以让它在 C 和 C++ 上运行?
void foo(void* b)
{
int *c = b;
printf("%d\n",*c);
}
int main ()
{
int a = 1000;
foo(&a);
return 0;
}
输出:
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
请帮忙
最佳答案
invalid conversion from
void*
toint*
为了将 void*
转换为 int*
,您需要将 b
转换为 int*
将其分配给 c
时。做:
int *c = (int*) b;
这适用于 C++ 和 C。
关于c++ - C++ 与 C 中函数调用中的 void 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43176129/