2011-03-23 54 views
0

我有一些Foo类,我想按如下操作。我有一些指向Foo对象的静态实例,然后,在一些函数中,我希望有一个可以充当它们的通用指针。例如,如何别名指针

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

这是我没有料到它的工作,但它似乎并没有被正常。通常情况如何?当我使用它时,我要么实际上是foo1或foo2。

+2

您能详细一点它是如何运作的,你期待什么? – fbrereto 2011-03-23 23:42:22

+0

这是一个指针是什么 - 什么不工作? – 2011-03-23 23:42:50

+2

代码你,你说你要 – pajton 2011-03-23 23:46:18

回答

0

它为我

#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

3

我猜你是在分配foo1和foo2之前分配的。你的代码贴出转让或者要么foo1或foo2的的当前价值,而不是到未来值。为了在foo1或foo2更改后保持正确,它需要是指向它所引用的指针。

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

由于这两个现在是一个指针的指针的对象,则需要取消对它的引用才可使用。例如:

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的变化。