在 C++ 中取消引用 void 指针 [英] Dereferencing the void pointer in C++

查看:30
本文介绍了在 C++ 中取消引用 void 指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个通用链表.该节点的结构如下 -

I'm trying to implement a generic linked list. The struct for the node is as follows -

typedef struct node{
        void *data;
        node *next;      
};

现在,当我尝试为数据分配地址时,假设例如 int,例如 -

Now, when I try to assign an address to the data, suppose for example for an int, like -

int n1=6;
node *temp;
temp = (node*)malloc(sizeof(node));
temp->data=&n1;

如何从节点获取 n1 的值?如果我说 -

How can I get the value of n1 from the node? If I say -

cout<<(*(temp->data));

我明白了 -

`void*' is not a pointer-to-object type 

当我为它分配一个 int 地址时,void 指针不会被类型转换为 int 指针类型吗?

Doesn't void pointer get typecasted to int pointer type when I assign an address of int to it?

推荐答案

您必须首先将 void* 类型转换为实际有效的指针类型(例如 int*)到告诉编译器您希望取消引用多少内存.

You must first typecast the void* to actual valid type of pointer (e.g int*) to tell the compiler how much memory you are expecting to dereference.

这篇关于在 C++ 中取消引用 void 指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆