c - 在 c 中访问/使用 void 指针时出错

标签 c pointers linked-list void

所以我有这个链表打印函数,它给我错误:

error: invalid use of void expression

这是导致此错误的行:

printf("[%d] -> ", *(link->pointer)); /*note: i tried to cast it to (int) but still     same error. */

这是我的链接结构;非常直接:

typedef struct DLLNode {
    void * pointer;
    struct DLLNode *next;
    struct DLLNode *previous;
} DLLNode;

我这样使用我的前置函数:

...
int j = 2;
prepend(&j, list);
...

因此它使用指向变量 2 的指针作为结构存储在新 DLLNode 中的值作为指针。

谁能告诉我为什么会这样,这意味着什么?感谢您的宝贵时间。

最佳答案

我想您正在尝试打印 link->pointer 指向的值。
printf("[%d] -> ", var) 希望在其参数列表中看到一个整数或可以转换为它的东西(例如,一个字符)。

link->pointervoid * 类型,在取消引用后,它看起来像一个 void 类型的变量。因此,编译器无法将 *(link->pointer) 转换为 int 类型。要告诉它您实际上在 void * 指针后面保留了一个整数值,您需要将 link->pointer 显式转换为 int * 类型,正如 Kaz 在评论中指出的那样,然后才取消引用它。我希望下面的代码能更清楚地说明这一点:

DLLNode *list;
// initialization and other stuff

void *p = list->pointer;
int *p_i;
p_i = (int*)p; // explicit cast to int*

// print the integer value pointed to by the list->pointer
printf("[%d] -> ", *p_i);

关于c - 在 c 中访问/使用 void 指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20013319/

相关文章:

c - 如何在 C 中将文本文件拆分为多个部分?

c - C for Windows 32 控制台应用程序中的计时器事件

c - 在STM32 Eval板上访问malloc声明的数组

json - 使用json解码转换接口(interface)

c - 从txt文件C中读取整数

c - 理解 argv 和 *++argv[0]

c - 链表不打印?

c - 如何获取 `C` 中对象指针的指针

python - 在多路树或连通图中查找一组元素/节点的根元素

c - 从文件中读取数据并将其写入链表