Reputation:
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
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
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