0

I have the following code:

#include <stdio.h>
#include <stdlib.h>

struct Book {
    char title[50];
    char author[50];
    char subject[100];
    int numPages;
    int numBooks;

    int (*p) (int *, int *);
};

int sum (int *a, int *b) {
    return *a + *b;
}

int main() {
    struct Book var;
    var.numPages = 7;
    var.numBooks = 9;
    int allPages = (*var.p) (&var.numPages, &var.numBooks);

    printf("%d\n", allPages);
    return (EXIT_SUCCESS);
}

I trying to use function in struct but my program have no result, no warning although I used -Wall, -Wextra. I'm a newbie. Hope everybody help.

  • 1
    You didn't set `p` to a valid function! You need `var.p = sum`. I'm surprised you didn't get an access violation. The behavior is undefined. The fact that it compiles without warnings doesn't catch something like that since it's a run time error. – lurker Dec 11 '15 at 17:05
  • `int main()` is not a valid signature for `main`. – too honest for this site Dec 11 '15 at 17:05

2 Answers2

2

var.p is not initialized (meaning it almost certainly doesn't refer to a valid function), creating undefined behavior. Use var.p = sum; to initialize it before the function call.

owacoder
  • 4,815
  • 20
  • 47
0

In your code you should first assign a function to a pointer and then by using a pointer call a function. for this your code should be

 int main()

  {
   struct Book var;
   var.numPages = 7;
   var.numBooks = 9;
   var.p=sum;

    int allPages =var.p(&var.numPages, &var.numBooks);

     printf("%d\n", allPages);
     return (EXIT_SUCCESS);
  }

for further information you can refer

C - function inside struct

Community
  • 1
  • 1
Nutan
  • 778
  • 1
  • 8
  • 18