core.stdc.stdlib._compare_fp_t and qsort
Dmitry Olshansky
dmitry.olsh at gmail.com
Sun Mar 18 18:11:02 UTC 2018
On Sunday, 18 March 2018 at 16:45:16 UTC, Joe wrote:
> On Sunday, 18 March 2018 at 13:10:08 UTC, Dmitry Olshansky
> wrote:
>> Do this to get the usual ptr + length:
>>
>> sort!((a, b) => to!string((*a).name) <
>> to!string((*b).name))(recs[]);
>>
>> Also to!string would be computed on each compare anew. May
>> want to use schwartzSort to avoid that, on 10 elements there
>> is no real difference though.
>
> The 10 elements are just because it's a small test program.
>
> What does changing "recs" to "recs[]" as the argument actually
> do? Does it duplicate the fixed array on the fly? [I guess I
> have to study more!]
No it just creates a pair of pointer to recs[0] + length of recs,
like this:
struct Array
{
size_t length;
Record* ptr;
}
In D it’s typed as Record[] and has a number of nice properties,
like not losing its length;)
> The change does pass the compiler, but at runtime it causes a
> segfault. The next to last frame in the backtrace shows
> (having changed from to!string to fromStringz and using a
> string template instead of a lambda):
Well since recs is array of pointers this looks like a null
pointer in your data.
The usual ways to fix that is either print stuff or poke around
in debugger to see if a Record* is null or .name is null.
> #6 0x0000555555565760 in
> std.algorithm.sorting.sort!("fromStringz((*a).name.ptr) <
> fromStringz((*b).name.ptr)", 0,
> testd.Record*[]).sort(testd.Record*[]) (r=...)
>
Also you don’t need (*a).name, D understands that . can access
data through pointer (what would be an error in C and require ->).
> Then it goes through quickSortImpl, shortSort and sort5, moving
> on to either std.functional.binaryFun or processing of the
> lambda, with a and b equal to 0, ending with a segfault in a ??
> call from fromStringz or in memcpy called from object._dup (in
> the to!string case).
More information about the Digitalmars-d-learn
mailing list