0
Follow
0
View

Can someone help me what's wrong with this bubble sort? [duplicate]

wxpxc75811 注册会员
2023-01-25 06:52

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)
dingyan124 注册会员
2023-01-25 06:52

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" (not length) when compared the second string.

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.

About the Author

Question Info

Publish Time
2023-01-25 06:52
Update Time
2023-01-25 06:52

Related Question