2009-11-12 73 views
0

使用結構structure2編寫一個程序來訪問函數「foo」。在結構中定義的訪問函數指針?

typedef struct 
{ 
    int *a; 
    char (*fptr)(char*); 
}structure1; 

typedef struct 
{ 
    int x; 
    structure1 *ptr; 
}structure2; 

char foo(char * c) 
{ 
--- 
--- 
--- 
} 
+0

這是功課? – 2009-11-12 09:48:44

回答

1
structure2 *s2 = (structure2*)malloc(sizeof(structure2)); 
s2->ptr = (structure1*)malloc(sizeof(structure1)); 
s2->ptr->fptr = foo; 
char x = 'a'; 
s2->ptr->fptr(&x); 
+0

糟糕..固定:) – Amarghosh 2009-11-12 10:15:43

0
  • 創建類型structure2
  • 分配給它structure1類型的對象(這可以在相當多的方式來完成)地址
  • 分配foo來分配structure1以上的目標對象的fptr成員使用
  • 呼叫foo

    structure2 s2; 
    // allocate 
    char c = 42; 
    s2.ptr->fptr(&c); // if this 
    

例子:

typedef struct 
{ 
    int *a; 
    char (*fptr)(char*); 
}structure1; 

typedef struct 
{ 
    int x; 
    structure1 *ptr; 
}structure2; 

char foo(char * c) 
{ 
return 'c'; 
} 

int main() 
{ 
structure1 s1; 
structure2 s2; 
s1.fptr = foo; 
s2.ptr = &s1; 
char c = 'c'; 
printf("%c\n", s2.ptr->fptr(&c)); 
return 0; 
}