【发布时间】:2020-10-24 10:03:32
【问题描述】:
我做了一个函数 f,它以 (void*) 作为输入,将其转换为 (int*) 并打印值。
#include <stdlib.h>
#include <stdio.h>
void f(void* p)
{
int *pi = (int*)p;
printf("%d\n", *pi);
}
int main()
{
int x = 1;
int *px = &x;
void *pv = (void*)px;
f(pv);
return 0;
}
是否可以实现一个功能:
void f2(void** pp);
这样它就可以执行函数 f? 的“相同”操作?我的目标是学习如何将 (int*) 转换为 (void**),反之亦然。
编辑:@tadman 代码的错误和警告(我做错了)
fvv.c: In function ‘f2’:
fvv.c:10:12: warning: initialization of ‘int *’ from incompatible pointer type ‘int **’ [-Wincompatible-pointer-types]
10 | int *pi = (int**)p;
| ^
fvv.c:12:17: error: invalid type argument of unary ‘*’ (have ‘int’)
12 | printf("%d\n", **pi);
|
EDIT2
fvv.c: In function ‘main’:
fvv.c:19:5: warning: passing argument 1 of ‘f2’ from incompatible pointer type [-Wincompatible-pointer-types]
19 | f2(&px);
| ^~~
| |
| int **
fvv.c:7:16: note: expected ‘void **’ but argument is of type ‘int **’
7 | void f2(void** p)
【问题讨论】:
-
你为什么要转换成
void**这样奇怪的东西? -
你好@tadman 我想学习如何做,因为我需要了解一些其他的库函数......并且因为我喜欢学习一种语言提供的所有可能性。跨度>
-
您确定要在不同的间接级别之间“转换”吗?例如之间的转换
void**和int **会稍微不那么令人担忧。 -
这有帮助吗,它实际上不是重复的,但似乎密切相关:stackoverflow.com/questions/58280538/…
标签: c pointers casting void-pointers