views:

148

answers:

2

Write a program to access the function "foo" using the structure structure2.

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

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

char foo(char * c)
{
---
---
---
}
A: 
  • Create an object of type structure2
  • Assign to it the address of an object of type structure1 (this can be done in quite a few ways)
  • Assign foo to the above allocated structure1 object's fptr member
  • Call foo using:

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

Example:

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;
}
dirkgently
+1  A: 
structure2 *s2 = (structure2*)malloc(sizeof(structure2));
s2->ptr = (structure1*)malloc(sizeof(structure1));
s2->ptr->fptr = foo;
char x = 'a';
s2->ptr->fptr(&x);
Amarghosh
Oops.. fixed :)
Amarghosh