Please do have a look at the attachment to get an idea of how it's supposed to look.
After opening a file, each line (containing <TITLE><space><PRICE><comma>) is read, and then a node is created which is to be inserted at a suitable (sorted) place. The relevant part of the code is:
Code:
typedef struct books {
char title[TITLE_LEN];
double price;
struct books *nxt_price;
struct books *nxt_title;
} booksT;
// Each line is scanned, then 'insert' is called.
for (i = 0, pos = 0; (feof(f) == 0); i++) {
fseek(f, pos, SEEK_CUR);
fscanf(f, "%s %lf", temp_title, &temp_price);
insert(titles, prices, temp_title, temp_price);
pos++;
}
void insert (booksT *titles[26], booksT *prices[10], char tmp_title[], double tmp_price) {
booksT *newnode, *runner;
int index;
newnode = (booksT*)malloc(sizeof(booksT*));
if (newnode == NULL) {
printf("Memory allocation error.\n");
exit(1);
}
strcpy(newnode->title, tmp_title);
newnode->price = tmp_price;
// Placement according to title.
index = newnode->title[0] - 'A';
if (titles[index] == NULL) {
titles[index] = newnode;
}
else {
runner = (booksT*)malloc(sizeof(booksT*));
if (runner == NULL) {
printf("Memory allocation error.\n");
exit(1);
}
strcpy(runner->title, newnode->title);
runner = titles[index];
for (runner = titles[index]; (runner->nxt_title != NULL) && (strcmp(runner->title, runner->nxt_title->title) < 0); runner = runner->nxt_title);
runner->nxt_title = newnode;
free(runner);
}
// Placement according to price.
index = (int)newnode->price / 10;
if (prices[index] == NULL) {
prices[index] = newnode;
}
else {
runner = (booksT*)malloc(sizeof(booksT*));
if (runner == NULL) {
printf("Memory allocation error.\n");
exit(1);
}
runner->price = newnode->price;
runner = prices[index];
for (runner = prices[index]; (runner->nxt_price != NULL) && (runner->price < runner->nxt_price->price); runner = runner->nxt_price);
runner->nxt_price = newnode;
free(runner);
}
}
Line 69 seems to be giving me a segmentation fault. Why would that be? Am I trying to insert the nodes incorrectly?