Program crashes

Hello, I am having troubles getting program to properly compare and sort a list of strings.

I don't have any errors so I believe it is something that makes the program think a true = false, or something like that. I am pretty new to debugging.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
void sortByAuthor(Book books[], int count)  // Here is where I have the problem.

{
    int alphaIndex;
    string temp;

    for(int i = 0; i < count; i++){      // library
        for(int h = i + 1; h < count; h++){  // unsorted list
            if(books[h].author < books[alphaIndex].author) 
                alphaIndex = h;  // Swap
        }
    temp = books[alphaIndex].author;
    books[alphaIndex] = books[i];
    books[i].author = temp;
    }
}

int showBooksByTitle (Book books[], int count, string title) // I don't think my problem is
                                                               // here but this section may be useful.
{
    int titleCount = 0;
    int match;

    for(int i = 0; i < 1000; i++)
    {
        match = books[i].title.find(title);
        if(match!= string::npos)
        {
            cout << endl << books[i].title << " (" << books[i].author << ")" << endl;
            titleCount++;
        }
    }
    cout << endl << titleCount << " records found." << endl;
    return 0;
}

 case 'T':  // Sample of cutput
        cout << endl << "Please enter all or part of the title: ";
        cin >> title;
        showBooksByTitle(books, count, title);
        sortByTitle(books, count);
        break;


Last edited on
What is the value of alphaIndex, and which element of the books array will it access?
The alphaIndex value = 0


1
2
3
4
5
6
7
8
struct Book
{
    string title;
    string author;
};

const int ARRAY_SIZE = 1000;
Book books [ARRAY_SIZE];
The alphaIndex value = 0


I meant here:
4
5
6
7
8
9
    int alphaIndex;    // alphaIndex is not initialised, it contains garbage
    string temp;

    for(int i = 0; i < count; i++){      // library
        for(int h = i + 1; h < count; h++){  // unsorted list
            if(books[h].author < books[alphaIndex].author) // alphaIndex still contains garbage 


Almost certainly you have an out of bounds array access, causing the program to crash.
Topic archived. No new replies allowed.