【发布时间】:2019-08-05 15:33:32
【问题描述】:
我经常看到 void 指针与其他类型的指针来回转换,我想知道为什么,我看到 malloc() 返回的 void 指针也需要在使用之前进行转换。
我对 C 语言非常陌生,并且来自 Python,所以指针是一个非常新的概念。
void * 指针的目的是提供一些“动态”类型吗?
以这段代码为例,它是有效的代码吗?
struct GenericStruct{
void *ptr;
};
// use void pointer to store an arbitrary type?
void store(struct GenericStruct *strct, int *myarr){
strct->ptr = (void *) myarr;
}
// use void pointer to load an arbitrary type as int*?
int *load(struct GenericStruct *strct){
return (int *) strct->ptr;
}
【问题讨论】:
-
C 中没有动态类型。类型描述了所需内存的大小和一些内置函数(如 +/- 等)的行为。指针的大小不取决于类型它指向虽然,但在你的操作系统上。接下来尝试理解指针算术,也许这可以帮助您更好地理解指针。除了来自莫斯科的@Vlad 回答之外,还非常简洁地回答了您的问题。
-
不需要转换
malloc返回的指针。而且你也不应该这样做。
标签: c pointers implicit-conversion void