zero_dev
zero_dev

Reputation: 653

struct has a function pointer to a function that takes a pointer of said struct .. need to predfine?

I'm trying to create a structure, that has a function pointer. That function pointer points to a function, that takes a pointer of said structure. This is a real chicken-or-the-egg problem because the prototype needs to know about the structure and the structure needs to know about the prototype. Is there a way to predefine the struct? I'm new to C so if anyone has any insight I would greatly appreciate it.

Thanks, -devnull

#include <stdio.h>
/* predefine struct person? */
void printInfo(struct person *);

struct person{
char *name;
int age;
const void *pf = printInfo;
};


int main(){

struct person master = {"Master", 23};  
return 0;
}

void printInfo(struct person *p){

printf("Name:\t%s\n", p->name);

}

Upvotes: 0

Views: 864

Answers (3)

Charles Keepax
Charles Keepax

Reputation: 2402

The only thing I would add is that all struct pointers have the same width and alignment (6.2.5/27 (C99 Standard)), so you don't actually require the forward definition of the struct.

Upvotes: 0

MByD
MByD

Reputation: 137322

You can add the struct person; before the function, but you cannot assign the function in struct person as far as I know,

#include <stdio.h>
struct person;
typedef void (FUNCTYPE)(struct person *);
void printInfo(struct person *);

struct person{
    char *name;
    int age;
    FUNCTYPE *pf;
};


int main(){

struct person master = {"Master", 23, printInfo};
    (master.pf)(&master);
    return 0;
}

void printInfo(struct person *p){
    printf("Name:\t%s\n", p->name);
}

The example above prints Name: Master

Upvotes: 1

user2100815
user2100815

Reputation:

struct person;

typedef void (*fp)(struct person*);

struct person {
    char * name;
    fp fptr;
};

void afunc( struct person * p ) {
    // stuff
}

int main() {
      struct person p = { "fred", afunc };
}

Upvotes: 1

Related Questions