Thread: Structure holds functions

  1. #1
    Registered User
    Join Date
    Jun 2006
    Posts
    3

    Structure holds functions

    hi

    i am new to c programming , as i learn structure can hold
    only variable, other structure ; but it is possible if i put function pointer inside structure then call it.. like bellow....

    Code:
    void testfunc()
    {
          
    }
    
    struct test
    {
           void (*testfunc)();
    
    };
    
    struct test *t1;
    
    t1->testfunc();  // this is how i want to call
    is it possible with c compiler?

    thanks
    atik

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >is it possible with c compiler?
    In the time it took to type that post, you could have fired up any compiler of your choice and tested it. But yes, it's possible.
    My best code is written with the delete key.

  3. #3
    Registered User Dante Shamest's Avatar
    Join Date
    Apr 2003
    Posts
    970
    Quote Originally Posted by atik
    but it is possible if i put function pointer inside structure then call it..
    It's possible. Here's an example.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void bar() {
      printf( "hello world!\n" ); 
    }
    
    typedef struct Foo {
      void (*func) ();
    } Foo ;
    
    int main()
    {
      Foo foo ;
      foo.func = bar ;
      foo.func() ;
      getchar();	
      return 0;
    }

  4. #4
    Registered User
    Join Date
    Jun 2006
    Posts
    3
    Quote Originally Posted by Prelude
    But yes, it's possible.
    thanks for reply...

    Can you pls give me an example that will call the function like this..

    Code:
    varName->functionName();
    and will compile without error..


    thanks again
    atik

  5. #5
    Registered User
    Join Date
    Jun 2006
    Posts
    3
    the code was posted while i was typing ..

    Thanks

    atik

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C interview questions
    By natrajdreams in forum C Programming
    Replies: 7
    Last Post: 12-12-2010, 12:40 PM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  3. Functions in a Class Structure?
    By AndyBomstad in forum C++ Programming
    Replies: 3
    Last Post: 06-15-2005, 04:51 AM
  4. Expression Manipulator v0.2 (bug fixes, functions)
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 05-26-2003, 04:52 PM
  5. structure arrays to functions
    By caws in forum C Programming
    Replies: 9
    Last Post: 04-13-2003, 03:37 PM