user2060964
user2060964

Reputation:

program crashing while bubble sorting?

            int sortAtt2,compare=0,counter=0;
            string tempTitle;
            for(int t=0; t<MAX_BOOKS; t++)
            {
                for(int i=0; i<MAX_BOOKS; i++)
                {
                    compare=(books[i+1].bookTitle).compare(books[i].bookTitle);
                    if(compare>0)
                    {
                        tempTitle=books[i].bookTitle;
                        books[i].bookTitle=books[i+1].bookTitle;
                        books[i+1].bookTitle=tempTitle;

                    }
                }
            }

this is my code, whenever I execute this function, the program crashes. Any idea why? I am comparing two strings here to bubble sort them.

Upvotes: 0

Views: 326

Answers (2)

Aesthete
Aesthete

Reputation: 18848

If you have MAX_BOOKS of 8.

Book books[MAX_BOOKS];

And you loop like this.

for(int i=0; i<MAX_BOOKS; i++)
{
  books[i+1];
}

What happens when i == 7?

Upvotes: 1

us2012
us2012

Reputation: 16253

Out-of bounds access. You are accessing books[i+1] in a loop where i counts up to MAX_BOOKS - 1, i,e, you are accessing books[MAX_BOOKS] - one past the end of an array with MAX_BOOKS elements.

Upvotes: 3

Related Questions