How to use the method Sort of the class TList in Delphi

762 Views Asked by At

How does the method Sort of the class TList work? Does this method only sort in a way that the elements of the list only ascend/descend? Please, have a look at the code below.

Type 
  PInteger = ^Integer;
Function Compare(Item1, Item2 : Pointer) : Integer;
Begin
 if PInteger(Item1)^ > Pinteger(Item2)^ then Result:= 1
 else if PInteger(Item1)^ < PInteger(Item2)^ then Result:= -1
 else Result:= 0;

End;
 { And, for instance, somewhere we call the method }
 List.Sort(Compare);

Now the thing is, after i compile the code, it works well, the list is sorted in a way that the elements ascend. But i don't understand the following line:

PInteger(item1)^ // What does this represent?

And what item1, item2 pointers point to? Do they not need to be initialized?

1

There are 1 best solutions below

2
On

First what PInteger(item1)^ does/represent?

  1. Item1 is a Pointer, the address of an item stored in the TPointerList.
  2. PInteger is a typed pointer, this means that this pointer points to an address where it is expected to find an integer (four bytes).
  3. ^ the dereferencing symbol, you can use this with pointers to tell the compiler that you want to use the data stored in the address that the pointer is currently pointing to
  4. PInteger(item1)^ you are performing a typecast. in other words you are telling the compiler to treat the pointer Item1 as if it was PInteger then you dereference it to use its data/value stored at the address Item1

Now back to your code. Your function expects two pointers to Items (Integers) from the list which then you compare the data stored in those address (by dereferencing). This means that the list is responsible for the pointers given to your function, in fact if the ItemCount is less than 1 your function will not be executed.

Note: you need to understand that this function will fail if the pointers are pointing to something other than integers (or give an undefined behavior).