void test(void *a)
{
int *h = a; //error
}
int main(int argc, char const* argv[])
{
int z = 13;
test(&z);
return 0;
}
如果我想保留 void *a 作为测试函数,如何使错误行正常工作?
最佳答案
我能够使用 gcc
编译并运行以下内容,而不会出现警告或错误:
#include <stdio.h>
void test(void *a)
{
int *h = a;
printf("test: %d\n", *h);
}
int main(int argc, char const* argv[])
{
int z = 13;
test(&z);
return 0;
}
您在指定的行上收到错误的唯一可能的原因是您正在使用 C++ 编译器(也许是 g++?)。如果我尝试这样做,则会收到以下错误:
error: invalid conversion from ‘void*’ to ‘int*’
If you need to use a C++ compiler, you need to explicitly cast a
to an int *
:
int *h = (int *) a;
这一更改允许此代码也可以使用 g++
进行编译。
关于c - 在c中通过引用传递int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41002986/