C 取消引用void*指针,结构数组
我试图将void*指针更改为结构数组。 关键是要将全局可见指针初始化为NULL,当main启动时,该指针将转换为结构数组 这里是一个最小的例子C 取消引用void*指针,结构数组,c,C,我试图将void*指针更改为结构数组。 关键是要将全局可见指针初始化为NULL,当main启动时,该指针将转换为结构数组 这里是一个最小的例子 #include <stdio.h> #include <stdlib.h> #include <string.h> void * hashtable; struct bucket { int a; int b; }; int main (void) { hashtable = (stru
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void * hashtable;
struct bucket {
int a;
int b;
};
int main (void)
{
hashtable = (struct bucket)malloc(6*sizeof(struct bucket));
int i ;
//for(i=0;i<6;i++)
// hashtable[i] = malloc(sizeof(struct bucket));
*(struct bucket)hashtable[0]->a = 12;
return 0;
}
如前所述,您不应该在此处强制转换
malloc()
的结果:
hashtable = (struct bucket)malloc(6*sizeof(struct bucket));
将其精简为:
hashtable = malloc(6*sizeof(struct bucket));
关于你的任务:
*(struct bucket)hashtable[0]->a = 12;
hashtable[0]->a
,但这会向您发出编译器警告,因为您尚未强制转换hashtable
([]
和->
的值高于强制转换)struct bucket*
,因为hashtable
是指针*
和->
操作符hashtable
的第一个元素的a
,如下所示:
((struct bucket *)hashtable)[0].a = 12;
当然,定义
struct bucket*hashtable可能会更容易
避免每次您想使用哈希表时都强制转换它。*(struct bucket)哈希表[0]->a=12代码>==>((结构桶*)哈希表)->a=12代码>为什么要携带struct?使用typedef。这有点帮助。但现在我得到了“test.c:16:52:error:conversion to non-scalar type requested hashtable=(struct bucket)malloc(6*sizeof(struct bucket));”最好使用struct bucket*hashtable代码>在struct
定义之后。“正在尝试将void*指针更改为结构数组。”为什么要使用void*
?提示:停止强制转换malloc()
的结果。它是不需要的,代码无论如何都做得不对。
((struct bucket *)hashtable)[0].a = 12;