PvzAKho - 10 months ago 35

C++ Question

Does anyone know how to convert this line from C++ to C programming language?

i wrote this code in C++ and i want to convert it in C.

`bool compare(string a, string b)`

{

return a+b > b+a;

}

it's a compare function in qsort

i want to compare by "a+b > b+a" to solve that problem:Such as if there are 4 integers as 123, 124, 56, 90 then the following integers can be made "1231245690, 1241235690, 5612312490, 9012312456, 9056124123" etc. In fact 24 such integers can be made. But one thing is sure that 9056124123 is the largest possible integer which can be made.

Answer

This will do what you expect without any concatenation:

```
int compare(char *a, char *b)
{
char *p1, *p2;
int i, len = strlen(a) + strlen(b);
p1 = a;
p2 = b;
for (i=0;i<len;i++) {
if (*p1 > *p2) {
return 1;
} else if (*p1 < *p2) {
return -1;
}
p1++;
p2++;
if (!*p1) {
p1 = b;
}
if (!*p2) {
p2 = a;
}
}
return 0;
}
```

The pointers `p1`

and `p2`

start at the beginning of `a`

and `b`

respectively and compare character by character for each one, then each pointer is incremented if there's no difference. When either pointer encounters a null byte, it is reassigned to the start of the other variable to continue from there.

We start by getting the combined length of the two strings and run through the loop that many times.

Working on the decimal representation of the two numbers as strings is actually simpler than dealing with them as integers, as the latter would involve determining the number of decimal digits and multiplying accordingly. This method also isn't constrained by the bounds of whatever integer type you may be using.

Source (Stackoverflow)