我正在尝试将 void * 指针更改为结构数组。\n重点是将全局可见指针初始化为 NULL,当 main 启动时,该指针将转换为结构数组\n 这是一个最小的示例。
\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid * hashtable;\n\nstruct bucket {\n int a;\n int b;\n};\n\nint main (void)\n{\n hashtable = (struct bucket)malloc(6*sizeof(struct bucket));\n int i ;\n //for(i=0;i<6;i++)\n // hashtable[i] = malloc(sizeof(struct bucket));\n\n *(struct bucket)hashtable[0]->a = 12;\n\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我得到的错误是:
\n\ntest.c:16:52: error: conversion to non-scalar type requested\n hashtable = (struct bucket)malloc(6*sizeof(struct bucket));\n ^\ntest.c:21:27: warning: dereferencing \xe2\x80\x98void *\xe2\x80\x99 pointer\n *(struct bucket)hashtable[0]->a = 12;\n ^\ntest.c:21:27: error: void value not ignored as it ought to be\nRun Code Online (Sandbox Code Playgroud)\n
如前所述,您不应该在malloc()此处投射结果:
hashtable = (struct bucket)malloc(6*sizeof(struct bucket));
Run Code Online (Sandbox Code Playgroud)
将其修剪为:
hashtable = malloc(6*sizeof(struct bucket));
Run Code Online (Sandbox Code Playgroud)
至于你的任务:
*(struct bucket)hashtable[0]->a = 12;
Run Code Online (Sandbox Code Playgroud)
您的程序首先尝试计算hashtable[0]->a,但这会向您发出编译器警告,因为您尚未进行强制转换hashtable([]并且->具有比强制转换更高的优先级)。
您需要强制转换为,struct bucket *因为它hashtable是一个指针。
您尝试取消引用的hashtable次数过多;您不需要额外的*和->运算符。
考虑到这一点,您可以按如下方式访问a的hashtable第一个元素:
((struct bucket *)hashtable)[0].a = 12;
Run Code Online (Sandbox Code Playgroud)
当然,您可能可以更轻松地进行定义struct bucket * hashtable;,以避免hashtable每次想要工作时都进行强制转换。
| 归档时间: |
|
| 查看次数: |
1472 次 |
| 最近记录: |