如何将 void 指针类型转换为 int 指针,然后在其中存储 int
How to typecast a void pointer to an int pointer and then store an int in it?
1. void* x;
2. x = new int [10];
3. x = static_cast<int*>(x);
4. *x = 2;
在第 4 行,我得到:error: ‘void*’ is not a pointer-to-object type
您需要定义新的指针类型。
静态强制转换了 x,但在静态强制转换后类型信息丢失,因为在声明时 x 无效*。
X将在他的一生中坚持空虚*。
这是一个工作代码示例:
void* x;
int* ptr;
x = new int[10];
ptr = static_cast<int*>(x);
*ptr = 2;
或者,您可以在同一行中分配和投射:
*(static_cast<int*>(x)) = 2;
由于任何指针(指向成员的指针和指向函数的指针除外,它们完全是其他东西(都可以隐式转换为 void 指针,因此您的第 2 行隐式将new int[10]
的结果从 int *
转换为 void *
。
同样,您的第 3 行显式将x
转换为int *
(static_cast
(,其结果被隐式转换回并存储在 x
中。 这没有净效应。 如果编译器足够聪明,它将完全忽略该语句。
您需要做的是引入另一个变量,它是指向int
的指针。
void *x;
x = new int[10];
int *y = static_cast<int *>(x);
*y = 2;
如果你真的想使用一个没有任何变量的 void 指针,那就是 int 指针,请这样做;
void *x;
x = new int[10];
*(static_cast<int *>(x)) = 2;
这是极其丑陋的,只有在特殊情况下才需要。
在实践中,除非你需要 void 指针来表示其他特定内容,否则请完全消除它。
int *x;
x = new int[10];
*x = 2;
事实上,不需要使用任何显式类型转换,这使得这也不太容易出错。
相关文章:
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 指针问题:从不兼容的类型"int"分配给"int *"
- 运行时错误:引用绑定到类型为"int"的空指针
- C++:将值 int(例如:0x00AAFAD8)转换为指针(指针本身也是 0x00AAFAD8 值)
- 如何将 int 指针转换为浮点指针
- 使用 int 指针的浮点数的位表示形式
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 从类指针到 int 的转换无效
- f 是指向函数的指针,该函数采用 int,并返回指向不带任何内容并返回双精度的函数的指针
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 为什么当我尝试将char输入到int时,文件指针会卡住
- 类型别名允许分配任意指针,尽管 int* 是必需的
- 为什么 fdump-class-hierarchy 为虚函数提供了两个指针 int vtable
- 双指针 (int**) 和双括号,用于从 2D 数组中获取值
- (C++)通过指针递增,或者:为什么这不起作用?指针->int = 指针->int+1;
- (c++)将int转换为char指针(int是int形式的字符)
- 如何使用指针到指针 (int **) 分配一维数组
- 删除地图中的指针<int,A*>
- 如何将字符串内存地址(如 "7fefe05a8")存储在 C++ 中的指针/int 变量中,以便我可以对其进行位屏蔽?
- 指向包含向量问题的实例类的指针<int>