I am trying to learn to access an array of structs. The following code compiles but seg faults (core dump) when executed. What have I done wrong?
#include <stdio.h>
#include <string.h>
// data structure
struct book {
int book_id; // book id
int (*ptFunc) ( struct book ); // addr of printBook function
char title[50]; // book title
char author[50]; // book author
};
struct book aBooks[10];
/*************************************************************************
* main *
*************************************************************************/
void printBook ( struct book aBooks[], int id ) {
printf ( "book_id : %d\n", aBooks[id].book_id ); // access to struct
printf ( "func addr : %p\n", aBooks[id].ptFunc ); // pointer to funcion
printf ( "title : %s\n", aBooks[id].title ); // string
printf ( "author : %s\n", aBooks[id].author ); // string
printf ( "\n" );
}
int main (void) {
strcpy ( aBooks[0].book_id, 0 );
strcpy ( aBooks[0].ptFunc, printBook );
strcpy ( aBooks[0].title, "This Little Piggy" );
strcpy ( aBooks[0].author, "Bad Wolf" );
printBook (aBooks, 0 ); // function to show selected data
return 0;
}
Solution: Copy and paste got me! (I had the pointer to a function working and then added assigning a string and copy and pasted too much!) With the help of "chrslg", the assignment section should have been:
aBooks[0].book_id = 0 ;
aBooks[0].prtFunc = printBook;
strcpy ( aBooks[0].title, "This Little Piggy" );
strcpy ( aBooks[0].author, "Bad Wolf" );
[ Thanks for the help, I did not know there was a difference between "Super User" and "Stack Overflow", I learned something! ]