Problem with function pointer in structure

J

jb.simon

Given the following code :


#include <stdio.h>

typedef struct Handler
{
int data1 ;
int data2 ;
int data3 ;

void ( *cb ) ( Handler * ) ;
} Handler ;

void callBack ( Handler * handler ) ;

int main ( void )
{

Handler myHandler ;

myHandler.cb = callBack ;

myHandler.cb ( &myHandler ) ;


return 0 ;
}

void callBack ( Handler * handler )
{
printf ( "\nData 1 = %d\n\n", handler->data1 ) ;
}

When I compile it I get:
/export/SAN1/simonj/test/typedef > gcc -std=c89 -Wall -pedantic test.c
test.c:10: error: parse error before '*' token

Any ideas ?

Thanks !
Joe
 
I

Ian Collins

Given the following code :


#include <stdio.h>

typedef struct Handler
{
int data1 ;
int data2 ;
int data3 ;

void ( *cb ) ( Handler * ) ;
} Handler ;
typedef struct Handler Handler;

struct Handler
{
int data1 ;
int data2 ;
int data3 ;

void ( *cb ) ( Handler * ) ;
};

or

typedef struct Handler
{
int data1 ;
int data2 ;
int data3 ;

void ( *cb ) ( struct Handler * ) ;
} Handler;

The typedef has to come before the use.
 
D

dada

Ian said:
typedef struct Handler Handler;

struct Handler
{
int data1 ;
int data2 ;
int data3 ;

void ( *cb ) ( Handler * ) ;
};

or

typedef struct Handler
{
int data1 ;
int data2 ;
int data3 ;

void ( *cb ) ( struct Handler * ) ;
} Handler;

The typedef has to come before the use.

OK thanks...
Joe
 
D

Duncan Muirhead

OK thanks...
Joe

There is an irritating wee gotcha if you want to define
a type for the call back. For that you need something like

struct bob;
typedef void (*bob_cb)( struct bob* );
typedef struct bob
{ int d;
bob_cb f;
} Bob;
(That is, you need a forward declaration of struct bob).

By analogy with
typedef struct joe
{ int d;
struct jim* f;
} Joe;
struct jim
{ int d;
};
which is ok, I had in my ignorance thought

typedef void (*cath_cb)( struct cath* );
struct cath
{ int d;
cath_cb f;
};
would be ok, but in fact it isn't (as the kind folks
here explained)
Duncan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,002
Messages
2,570,258
Members
46,858
Latest member
FlorrieTuf

Latest Threads

Top