Thank you guys, I implemented your ideas and they're working great!
There's only two problems now.
1) All titles and prices are read, but
-when linked according to title, some (eg "BDD" and "BDE") seem to get neglected ("BDE", in this case).
-when linked according to price, similar thing happens. Maybe there's something missing from the code?
Code:
void insert (booksT *titles[26], booksT *prices[10], char tmp_title[], double tmp_price) {
booksT *newnode, *curr, *prev;
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 {
curr = titles[index];
prev = NULL;
while (curr != NULL) {
if (strcmp(curr->title, newnode->title) > 0) {
if (prev) {
prev->nxt_title = newnode;
}
newnode->nxt_title = curr;
break;
}
prev = curr;
curr = curr->nxt_title;
}
if (curr == NULL) {
prev->nxt_title = newnode;
}
}
// Placement according to price.
index = (int)(newnode->price / 10.0);
index -= index * 10.0 == newnode->price;
if (prices[index] == NULL) {
prices[index] = newnode;
}
else {
curr = prices[index];
prev = NULL;
while (curr != NULL) {
if (curr->price > newnode->price) {
if (prev) {
prev->nxt_price = newnode;
}
newnode->nxt_price = curr;
break;
}
prev = curr;
curr = curr->nxt_price;
}
if (curr == NULL) {
prev->nxt_price = newnode;
}
}
}
or maybe when they're printed...
Code:
void save (enum output_specification spec, FILE *file, booksT *sortby[], int size) {
int i;
booksT *curr;
if (spec == by_title) {
for (i = 0; i < size; i++) {
if (sortby[i] != NULL) {
curr = sortby[i];
while (1) {
fprintf(file, "%lf (%s)\n", curr->price, curr->title);
fflush(file);
if (curr->nxt_title == NULL) {
break;
}
curr = curr->nxt_title;
}
}
}
fclose(file);
}
else {
for (i = 0; i < size; i++) {
if (sortby[i] != NULL) {
curr = sortby[i];
while (1) {
fprintf(file, "%s (%lf)\n", curr->title, curr->price);
fflush(file);
if (curr->nxt_price == NULL) {
break;
}
curr = curr->nxt_price;
}
}
}
fclose(file);
}
}
2) Tried to free all allocated memory using recursion, but I'm getting a segmentation fault. This is the part of the code that's relevant:
Code:
void memfree (booksT *titles[26], booksT *prices[10], int size_titles, int size_prices) {
booksT *runner;
int i;
for (i = 0; i < size_titles; i++) {
if (titles[i] != NULL) {
runner = titles[i];
}
clearList(runner);
titles[i] = NULL;
}
for (i = 0; i < size_prices; i++) {
if (prices[i] != NULL) {
prices[i] = NULL; // Nodes have been freed by the previous loop so I only do this.
}
}
}
void clearList(booksT *head) {
if (head == NULL) {
return;
}
else {
clearList(head->nxt_title);
free(head);
head = NULL;
}
}
Any thoughts?