Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C array struct function pointer

How do you create a function pointer with struct table such as

static struct {
  int pid;
  int queue[MAXPROCS];
} semtab[MAXSEMS];

I think I understand how to make OO equivalent in C using function pointer with this post, but how can I do with when my struct is an array. I'm still a little iffy with the syntax.

Would it be something like

static struct {
  int pid;
  int queue[MAXPROCS];

  void (*fncPtr_enqueue)(int) = enqueue;
                 // or is it void(*enqueue)(semtable[]*) ?
  int (*fcnPtr_dequeue)() = dequeue;
} semtab[MAXSEMS];

void enqueue(int i) { /* code */ }
int dequeue() { /* code */ }


// then to use it, it would be like this?
void foo() {
  semtab[5].enqueue(6);
}
like image 583
Sugihara Avatar asked Jul 18 '26 19:07

Sugihara


1 Answers

Use

static struct {
  int pid;
  int queue[MAXPROCS];

  void (*fncPtr_enqueue)(int); // This defines a member fncPtr_enqueue
  int (*fncPtr_dequeue)();     // Note that you had fcnPtr_ in your post.
                               // I have fncPtr_ here.
} semtab[MAXSEMS];

void enqueue(int i) { /* code */ }
int dequeue() { /* code */ }

Each object in semtab that needs to have valid function pointers needs to be updated.

semtab[0].fncPtr_enqueue = enqueue;
semtab[0].fncPtr_dequeue = dequeue;
like image 134
R Sahu Avatar answered Jul 20 '26 08:07

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!