sorting structure members using pointers
Hello, I am working through the book C Primer Plus by Stephen Prata, and am stuck on problem 3 in Chapter 14. I have no classmates or teachers, and cannot for the life of me see why this thing won't sort.
The structure, along with the function that will sort the members that are the 'title' strings, is here:e in the sorting part, though I am using a simple "bubble sort" that should work.
Can anyone see what I am missing?
Code:
struct book { /* set up book template */
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
/* this function will output the books by alpabetized titles */
void print_by_title(const struct book * ptr, int totl)
{
int i; /* an index */
/* i will range from 0 to < totl */
int array[totl]; /* this array will hold the indices of */
/* the books, but will be in alphabetical */
/* order. */
int outer; /* used in sorting */
int inner; /* used in sorting */
int temp; /* used in sorting */
/* initialize array[] */
for(i = 0; i < totl; i++)
array[i] = i;
/* Alphabetize the list according to titles. That is, */
/* sort the indices of array[]. */
for(outer = 0; outer < totl; outer++)
for(inner = 0; inner < (totl - 1); inner++)
{
if(strcmp((ptr + inner)->title, (ptr + (inner + 1))->title) > 0)
{
temp = array[inner + 1];
array[inner + 1] = array[inner];
array[inner] = temp;
}
}
/* print out the book list according to alphabetized titles */
printf("\n");
printf("Here are the books alphabetized by title:\n");
printf("\n");
for(i = 0; i < totl; i++)
printf("%s by %s, $%.2f\n", (ptr + array[i])->title,
(ptr + array[i])->author, (ptr + array[i])->value);
Robert