简体   繁体   English

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

[英]Dereferencing void * pointer, array of structs

I am trying to change a void * pointer into an array of structs. 我正在尝试将void *指针更改为结构数组。 The point is to have a global visible pointer initialized to NULL, that when main starts, will be turned to an array of structs Here is a minimal example. 关键是要有一个初始化为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;
}

The errors I get are: 我得到的错误是:

test.c:16:52: error: conversion to non-scalar type requested
  hashtable = (struct bucket)malloc(6*sizeof(struct bucket));
                                                ^
test.c:21:27: warning: dereferencing ‘void *’ pointer
  *(struct bucket)hashtable[0]->a = 12;
                       ^
test.c:21:27: error: void value not ignored as it ought to be

As mentioned already, you shouldn't be casting the result of malloc() here: 如前所述,您不应在此处强制转换malloc()结果:

hashtable = (struct bucket)malloc(6*sizeof(struct bucket));

Trim it down to: 整理到:

hashtable = malloc(6*sizeof(struct bucket));

As for your assignment: 至于您的作业:

*(struct bucket)hashtable[0]->a = 12;
  1. Your program first tries to compute hashtable[0]->a , but that gives you that compiler warning since you haven't cast hashtable yet ( [] and -> have higher precedence than casting). 您的程序首先尝试计算hashtable[0]->a ,但这会向您发出编译器警告,因为您尚未强制转换hashtable[]-> 优先级高于强制转换)。

  2. You need to cast to struct bucket * since hashtable is a pointer. 您需要强制转换为struct bucket *因为hashtable是一个指针。

  3. You attempt to dereference hashtable too many times; 您尝试取消引用hashtable次数过多; you don't need the extra * and -> operators. 您不需要额外的*->运算符。

With this in mind, you can access a of hashtable 's first element as follows: 考虑到这一点,你可以访问ahashtable的第一个元素如下:

((struct bucket *)hashtable)[0].a = 12;

Of course, you might have an easier time defining struct bucket * hashtable; 当然,定义struct bucket * hashtable;可能会更容易struct bucket * hashtable; to avoid casting hashtable every time you want to work it. 避免在每次您想使用它时都强制转换hashtable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM