指向两个不同结构表的单指针

Single Pointer pointing to two different struct tables

本文关键字:指针 结构 单指针 两个      更新时间:2023-10-16

我已经阅读了下面的文章,但我仍然有同样的问题.....

如果我有一个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; 
 }