c++ - C++ 与 C 中函数调用中的 void 指针

标签 c++ c void-pointers

我有一段代码可以在 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* to int*

为了将 void* 转换为 int*,您需要将 b 转换为 int* 将其分配给 c 时。做:

int *c = (int*) b;

这适用于 C++ 和 C。

关于c++ - C++ 与 C 中函数调用中的 void 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43176129/

相关文章:

c - EXC_BAD_ACCESS 将字符写入 txt 文件

将文本从 C 文本文件复制到字符数组?

c++ - 将 void* 转换为动态类型

c++ - xlib XNextEvent 检查一个键是否被按下

c++ - 您可以在指向不同模板类实例的指针之间进行转换吗?

c++ - 使用 sprintf 打印十六进制值的便携方式

c++ - 防止虚函数在子类中重载两次

c - 为什么函数中全局静态变量优先于外部变量?

c - C语言结构中 "dereferencing ` void *' pointer"警告的解决方案?

c++ - 在 C++ 中删除 void* 指针