所以我有这个链表打印函数,它给我错误:
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->pointer
是 void *
类型,在取消引用后,它看起来像一个 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/