Joes Lie Joes Lie -4 years ago 145
C Question

sorting struct in C cant show output result in VS2017, but show in CodeBlocks

So basically I want to sort number in file. so i read first

for (int i = 0; i < count; i++) {
fscanf(read_file, "%d %s %d %s\n", &custid_temp[i].id, custid_temp[i].name, &custid_temp[i].reward_point, custid_temp[i].promo);
printf("%d %s %d %s\n", custid_temp[i].id, custid_temp[i].name, custid_temp[i].reward_point, custid_temp[i].promo);
}


The File consist of this:

1 Test 200 WELCOME2017
2 James 700 WELCOME2017


See it is the points, 200 and 700 in files, I want to sort in ascending order (largest to smallest) become like this:

2 James 700 WELCOME2017
1 Test 200 WELCOME2017


So I will sort the file using this function:

for (int i = 0; i<count+1; i++)
{
for (int j = 0; j<count - i; j++)
{
if (custid[j].reward_point <custid[j + 1].reward_point)
{
struct customer temp_sort = custid[j];
custid[j] = custid[j + 1];
custid[j + 1] = temp_sort;
}
}
}


And lastly print the updated struct:

for (int i = 0; i < count; i++) {
printf("%d %s %d %s\n", custid[i].id, custid[i].name, custid[i].reward_point, custid[i].promo);
}


The result is this(VS2017):

1 Test 200 WELCOME2017
2 James 700 WELCOME2017
0 0
0 0


The result is this(CodeBlocks):

1 Test 200 WELCOME2017
2 James 700 WELCOME2017
2 James 700 WELCOME2017
1 Test 200 WELCOME2017

Process returned 2 (0x2) execution time : 0.015 s
Press any key to continue.


How come two compiler produce 2 different result, even with the same code, is there any solution for this to work on VS2017?

Thanks for the time anyway.

Answer Source

Try to approach the sorting problem more generally. Define an order by implementing a comparator function to be able to decide, if an element is smaller, equal or greater than another element. Define a function interface, which takes your array and a function pointer to your comparator (taking two elements of your array as parameters and returning -1, 0 or 1 for smaller, equal or greater).

Finally use quicksort or another well-known algorithm to perform the actual sorting. Decide if you require the order to be total - a property which is desirable, if your sorting algorithm is supposed to return deterministic results.

More specifically, I'd encourage the use of qsort from the C standard library. It's pretty well documented: http://www.gnu.org/software/libc/manual/html_node/Search_002fSort-Example.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download