0

sort.hpp -> we sort station names

    struct _element {
    char icao_code[5];
    char station_name[100];
};

typedef struct _element element;

void bubbleSort(element* stations, int size);

bubblesort (doesn't work)

void bubbleSort(element *pElement, int size) {
int i, j;
for (i = 0; i < size - 1; i++)

    // Last i elements are already in place
    for (j = 0; j < size - i - 1; j++)
        if (pElement[j].station_name > pElement[j + 1].station_name)
        {
            element tmp = pElement[j];
            pElement[j] = pElement[i];
            pElement[i] = tmp;
        }
}

Does someone know how to make this code work?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 2
    In C use `strcmp()` to compare strings (not `>` to compare pointers)... I have no idea about C++. – pmg Jun 28 '22 at 08:36

2 Answers2

2

This is not the correct way to compare C strings

if (pElement[j].station_name > pElement[j + 1].station_name)

The problem is that you are comparing the pointers, not the characters that are pointed at.

Use strcmp instead

if (strcmp(pElement[j].station_name, pElement[j + 1].station_name) > 0)
john
  • 85,011
  • 4
  • 57
  • 81
2

The reason is because when you use relational operators (==,<,etc) to compare strings, C actually compares their addresses, not their contents.

To compare the contents of two strings you have you have to use strcmp().

strcmp(string1, string2);

strcmp() works by comparing each character's ASCII value. So, a value of 0 means that both strings are equal and you would test for that like this:

if(strcmp(string1, string2) ==0){
    printf("Both strings are equal!");
}

As a side note, it can also tell you if the first string is considered to be "bigger" or "smaller" in value (not length) when compared the second string.

For example:

strcmp("hello", "HELLO");

Will return a value bigger than 0 which means the ASCII values of "hello" add up to be higher than those of "HELLO". Meanwhile, a value less than 0 would mean that the first string is smaller than the second string.