我正在使用包含这段代码的库(我已经删除了不相关的部分)
// Represents user-defined data
typedef char* aiUserData;
...
struct aiFile
{
// Callback to write to a file
aiFileReadProc ReadProc;
// Callback to retrieve the current position of
// the file cursor (ftell())
aiFileTellProc TellProc;
...
// User-defined, opaque data
aiUserData UserData;
};
我需要使用最后一个结构属性 UserData
。为此目的使用结构会很方便,但是正如在第一行中看到的那样,UserData 被声明为 char *
类型。我在某处读到 char *
类似于 void *
。这是否意味着我可以做类似的事情:
.UserData = &MyDataStruct;
或者这不安全吗?
最佳答案
库设计不好,应该是void *
。
您可以合法地将任何指针转换为void *
,并将void *
转换为char *
,因此是安全的。
设置指针时,必须强制转换为char *
:
static struct mydata {
float pi;
} data; /* This is what we want to store. */
struct aiFile whatever;
whatever.UserData = (char *) &data;
以后当你想使用指针时,你必须进行反向转换:
struct mydata *d = (struct mydata *) whatever.UserData;
在实践中,您当然也会typedef
您的struct mydata
;为简洁起见,我省略了它。
如果库做了正确的事情并使用了 void *
,那么就不需要任何转换了。
关于c - char * 指针可以指向什么(是不是像 void *)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26486024/