【问题标题】:How to alias a pointer如何给指针起别名
【发布时间】:2011-03-23 23:41:03
【问题描述】:

我有一些类 Foo,我想做如下。我有一些指向 Foo 对象的静态实例,static Foo *foo1; static Foo *foo2;

然后,在某些函数中,我想要一个通用指针,可以同时充当它们。例如,

Foo *either;
if (some_variable == 1)
{
    either = foo1;
}
else
{
    either = foo2;
}

这是我预期的工作方式,但它似乎无法正常工作。一般是怎么做的?我想在使用它时实际上是 foo1 或 foo2。

【问题讨论】:

  • 您能否详细介绍一下它的运作方式以及您的预期?
  • 这就是指针的用途——什么不起作用?
  • 您提供的代码完全按照您的要求工作
  • 您需要提供 (1) 一些尝试执行此操作的实际代码,(2) 完全符合您的预期,(3) 它做了什么,以及 (4) 您如何知道这是它做了什么,如果这不是绝对明显的话。 (我怀疑“实际上是”这个词在这里的意思是有问题的。但我们会看到......)

标签: c


【解决方案1】:

我猜你是在分配 foo1 和 foo2 之前分配的。您发布的代码分配给 foo1 或 foo2 的 current 值,而不是 future 值。为了在 foo1 或 foo2 更改后保持正确,它需要是指向它所引用的指针。

static Foo *foo1, *foo2;
Foo **either;
if(some_variable == 1) {
    either = &foo1;
} else {
    either = &foo2;
}

由于 any 现在是指向对象指针的指针,因此您需要在使用前取消引用它。示例:

if(*either == foo1) printf("either is foo1\n");
    else if(*either == foo2) printf("either is foo2\n");
    else printf("either isn't foo1 or foo2\n");

此代码将允许在 foo1 或 foo2 更改之后继续指向任何 foo1 或 foo2。

【讨论】:

    【解决方案2】:

    对我有用

    #include <stdio.h>
    
    typedef struct Foo Foo;
    struct Foo {
      int data;
    };
    
    void test(Foo *foo1, Foo *foo2, int first) {
      Foo *either;
      if (first == 1)
      {
        either = foo1;
      }
      else
      {
        either = foo2;
      }
      printf("either->data is %d\n", either->data);
    }
    
    int main(void) {
      Foo bar, baz;
      bar.data = 42;
      baz.data = 2011;
      test(&bar, &baz, 0);
      test(&bar, &baz, 1);
      return 0;
    }
    

    也可通过codepad 获得。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 2021-06-13
      相关资源
      最近更新 更多