开发者

How to alias a pointer

I have some class Foo, and I want to do as follows. I have some static instances of pointers to Foo objects, static Foo *foo1; static Foo *foo2;

Then, in so开发者_JAVA百科me function, I want to have a generic pointer that can act as both of them. For example,

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

This is how I expected it to work, but it doesn't seem to be functioning correctly. How is it normally done? I want either to actually BE foo1 or foo2 when I use it.


I am guessing you are assigning either before assigning foo1 and foo2. The code you posted assigns either to the current value of either foo1 or foo2, not to the future value. In order to have either remain correct after foo1 or foo2 changes, it needs to be a pointer to whichever it is referencing.

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

Since either is now a pointer to a pointer to the object, you need to dereference it before use. Example:

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");

This code will allow either to continue to point to whatever foo1 or foo2 is after foo1 or foo2 change.


It works for me

#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;
}

Also available at codepad.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜