指向两个不同结构表的单指针
Single Pointer pointing to two different struct tables
我已经阅读了下面的文章,但我仍然有同样的问题.....
如果我有一个void指针,我在运行时转换到一个或其他结构,这里的问题似乎是什么?例如下面的伪代码
typedef struct A {
int x;
int y;
} A1;
typedef struct B {
int x;
int y;
} B1;
.......
A1 *a1;
B1 *b1;
void *prt;
a1 = new A1;
b1 = new B1;
prt = reinterpret_cast<A1>(a1); // ptr shows to a1 structure ?
prt = reinterpret_cast<B1>(b1); // ptr shows to b1 structure ?
ptr是否指向a1和b1结构体?
[单指针指向两个不同的结构表(查找表)在c
这个结构
typedef struct A {
int x;
int y;
} *A1;
定义了一个新的类型定义。它不是名称为A1的对象的声明。所以写
会更正确struct A {
int x;
int y;
} *A1;
如果你想让A1是一个对象
还可以将任意类型的指针赋值给void指针。所以你可以直接写
prt = A1;
prt = B1;
而不是这个无效代码
prt = reinterpret_cast<A>(A1);
prt = reinterpret_cast<B>(B1);
这些没有问题
prt = A1;
prt = B1;
作业。
如果你想用一个指针访问两个不同结构体的数据成员,那么你不能这样做,因为这两个结构体有不同的类型,而指针只能是一种类型。
如果你定义了这两个结构的并集,你可以做任何你想做的。
或者如果你指的是以下
#include <iostream>
int main ()
{
struct A
{
int x, y;
} a;
struct B
{
int x, y;
} b;
void *p = &a;
reinterpret_cast<A *>( p )->x = 10;
reinterpret_cast<A *>( p )->y = 20;
p = &b;
reinterpret_cast<B *>( p )->x = 30;
reinterpret_cast<B *>( p )->y = 40;
std::cout << "a: " << a.x << 't' << a.y << std::endl;
std::cout << "b: " << b.x << 't' << b.y << std::endl;
return 0;
}
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- 指针或结构的矢量
- MSVC将仅移动结构参数解释为指针
- 如何访问指针结构的成员变量?
- 如何将变量从变量传递到指针结构对象
- 如何在函数中检索指针结构
- C :变量的点地址至指针结构成员的地址
- C++指针结构不会被删除
- 初始化指针结构 - 内存中的外观
- C++指针结构和多线程
- c++中指针结构的运算符重载
- 为什么我不能转发声明指针结构?
- C# 如何定义新的指针结构
- 如何处理大型指针结构
- 我怎么能写一个函数的定义在模板类中声明返回指针结构对象
- 我如何编程指针结构或类变量在c++
- 具有指针结构的类所需的析构函数
- 为什么在非指针结构上进行类型转换会出现语法错误
- 语法:做binary_search (STL)排序向量的指针结构
- /a.检测到Glibc.out: munmap_chunk():无效指针- c++结构体的动态数组