C++ Can somebody tell me where the bug is? //bugsort1.cpp #include <iostream> us
ID: 3929916 • Letter: C
Question
C++ Can somebody tell me where the bug is? //bugsort1.cpp #include <iostream> using namespace std; class Citem { public: int key; char *data; }; Citem item_array[] = { { 3, "Arnold" }, { 2, "David" }, { 4, "Dianne" }, { 5, "Bill" }, { 1, "Barbara" } }; void sort( Citem a[], int n ) { int i = 0, j = 0, s = 1; for ( ; i < n && s != 0; i++ ){ s = 0; for ( j = 0; j < n; j++ ) { if ( a[j].key > a[j+1].key ) { Citem t = a[j]; a[j] = a[j+1]; a[j+1] = t; s++; } } n--; } } //sort int main() { sort( item_array, 5 ); cout << "Sorted items : " << endl; for ( int i = 0; i < 5; i++ ) { cout << "item_array[" << i << "]= (" << item_array[i].key << ", " << item_array[i].data << " )" << endl; } }
Explanation / Answer
The bug is in the following line of code.
In place of this you can use the following code:-
public:
int key;
char const *data;
};
The reason for this is:-
In C the type is array of char and in C++ it is constant array of char. In any case, you are not allowed to change the characters of the string literal, so the const in C++ is not really a restriction but more of a type safety thing. A conversion from const char* to char* is generally not possible without an explicit cast for safety reasons. But for backwards compatibility with C the language C++ still allows assigning a string literal to a char* and gives you a warning about this conversion being deprecated.
There was some problem with the logic of sorting which is used, The correct code to do sorting in ascending order is as follows:-
#include <iostream>
using namespace std;
class Citem {
public:
int key;
char const *data;
};
Citem item_array[] = {
{ 3, "Arnold" },
{ 2, "David" },
{ 4, "Dianne" },
{ 5, "Bill" },
{ 1, "Barbara" }
};
void sort( Citem a[], int n )
{
int i = 0, j = 0, s = 1;
for (i = 0; i < n; i++ )
{
for (j = i + 1; j <= n; j++ )
{
if ( a[j].key > a[i].key )
{
Citem t = a[i];
a[i]= a[j];
a[j] = t;
}
}
//n--;
}
} //sort
int main()
{
sort( item_array, 5 );
cout << "Sorted items : " << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "item_array[" << i << "]= (" << item_array[i].key
<< ", " << item_array[i].data << " )" << endl;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.