Dereferencing the void pointer in C++(在 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 指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中取消引用 void 指针
基础教程推荐
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
