Thread: Function pointer

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    61

    Function pointer

    Hi! I want to have a function pointer inside a typedef struct but I get a segmentation fault when I run my code. Here's my code:

    Code:
    #include <stdio.h>
    
    typedef struct Foo {
    	void (*bar)(int);
    } Foo;
    
    
    void func(int x) {
        printf("display: %d\n", x);
    }
    
    
    int main() {
    	Foo* foo = NULL;
    
    
    	foo -> bar = &func;
    
    
        foo -> bar(1);
        
        return 0;
    }
    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    You could try making foo point somewhere, rather than at NULL.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2012
    Posts
    61
    Haha I'm sorry I forgot to use malloc.

    Code:
    Foo* foo = (Foo*)malloc(sizeof(Foo));

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-14-2013, 03:25 PM
  2. Function pointer and Member function pointer usage?
    By freiza in forum C++ Programming
    Replies: 4
    Last Post: 05-30-2012, 08:17 AM
  3. Replies: 7
    Last Post: 07-04-2007, 12:46 PM
  4. Replies: 9
    Last Post: 01-02-2007, 04:22 PM
  5. Replies: 4
    Last Post: 11-05-2006, 02:57 PM