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 指针
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
