C 取消引用void*指针,结构数组

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

我试图将void*指针更改为结构数组。 关键是要将全局可见指针初始化为NULL,当main启动时,该指针将转换为结构数组 这里是一个最小的例子

#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;