The first program below calls a function using a pointer. I am now trying to get the same mechanism to work using an array of structs. The last line (commented out) will not work. What am I doing wrong?
This works...
This does not work...
This works...
C:
#include <stdio.h>
#include <string.h>
void func(int a) { // normal function
printf("Value of a is %d\n", a);
}
int main() {
void (*func_ptr)(int) = func; // assign ptr to func address
func_ptr(10); // call func
return 0;
}
This does not work...
C:
#include <stdio.h>
#include <string.h>
// data structure
struct book {
int book_id; // book id
int (*prtFunc) ( struct book ); // addr of print function
char title[50]; // book title
char author[50]; // book author
};
struct book arBookList[10];
void printBook ( struct book arBookList[], int id ) {
printf ( "book_id : %d\n", arBookList[id].book_id ); // access to struc
printf ( "func addr : %p\n", arBookList[id].prtFunc );
printf ( "title : %s\n", arBookList[id].title );
printf ( "author : %s\n", arBookList[id].author ); // access to a struc in struc
printf ( "\n" );
}
int main ( ) {
arBookList[0].book_id = 0 ;
arBookList[0].prtFunc = printBook;
strcpy ( arBookList[0].title, "This Little Piggy" );
strcpy ( arBookList[0].author, "Bad Wolf" );
printBook (arBookList, 0 ); // show data using function call
arBookList[1].book_id = 1 ;
arBookList[1].prtFunc = printBook;
strcpy ( arBookList[1].title, "Mary Had a Lamb" );
strcpy ( arBookList[1].author, "Snow Fleece" );
printBook (arBookList, 1 ); // show data using function call
// call function using pointer
void (*func_ptr)(struct book, int) = printBook; // assign ptr to func address
// func_ptr (arBookList, 1 ); // <--- does not work, why ???
return 0;
}