I am trying to implement bubble sort the function bubbleSort(names, size) and test it with my driver code. I get error on the driver code when I call the function. I would like to know how to set the first parameter correctly when I call the function.
I get two errors which is related to the first parameter "names".
Error (active) E0167 argument of type "char *" is incompatible with parameter of type "char **"
Error C2664 'void bubbleSort(char *[],const int)': cannot convert argument 1 from 'char [8]' to 'char *[]'
I am using Windows 10 Pro (64 bit) with Visual Studio Community 2019. Thank you in advance for your help.
#include <iostream>
#include <string.h>
using namespace std;
enum Bool { TRUE, FALSE };
void bubbleSort(char *names[], const int size)
{
Bool swapped;
char* temp;
for (int i = 0; i < size; i)
{
swapped = FALSE;
for (int j = 0; j < size - i - 1; j)
{
if (names[j] > names[j 1])
{
temp = names[j];
names[j] = names[j 1];
names[j 1] = temp;
swapped = TRUE;
}
}
// if no two elements were swapped by inner loop, then break
if (swapped == FALSE)
{
break;
}
}
}
int main()
{
char names[] = {'s', 'a', 'c', 'd', 'i', 'd', 'm', 'o'};
int size = 8;
bubbleSort(names, size); // i get error here for 'names'
for (int i = 0; i < size; i)
cout << names[i] << " " << endl;
}
CodePudding user response:
Your sort function wants an array of C-strings, but you are passing it an array of characters. Hence the error.
To sort an array of characters, try this:
#include <iostream>
using namespace std;
void bubbleSort(char names[], const int size)
{
bool swapped;
char temp;
for (int i = 0; i < size; i)
{
swapped = false;
for (int j = 0; j < size - i - 1; j)
{
if (names[j] > names[j 1])
{
temp = names[j];
names[j] = names[j 1];
names[j 1] = temp;
swapped = true;
}
}
// if no two elements were swapped by inner loop, then break
if (!swapped)
{
break;
}
}
}
int main()
{
char names[] = {'s', 'a', 'c', 'd', 'i', 'd', 'm', 'o'};
int size = 8;
bubbleSort(names, size);
for (int i = 0; i < size; i)
cout << names[i] << " " << endl;
}
Alternatively, to sort an array of C-strings, try this:
#include <iostream>
#include <cstring>
using namespace std;
void bubbleSort(const char* names[], const int size)
{
bool swapped;
const char* temp;
for (int i = 0; i < size; i)
{
swapped = false;
for (int j = 0; j < size - i - 1; j)
{
if (strcmp(names[j], names[j 1]) > 0)
{
temp = names[j];
names[j] = names[j 1];
names[j 1] = temp;
swapped = true;
}
}
// if no two elements were swapped by inner loop, then break
if (!swapped)
{
break;
}
}
}
int main()
{
const char* names[] = {"s", "a", "c", "d", "i", "d", "m", "o"};
int size = 8;
bubbleSort(names, size);
for (int i = 0; i < size; i)
cout << names[i] << " " << endl;
}