views:

253

answers:

2

Hello,

In my app, i've created the TList type list where i store the pointers to 1 string and 2 float(real) values for every 3 items.

aList.Add(@sName); //string
aList.Add(@x1); //float
aList.Add(@x2); //float

Then, i want to get the values out from the list, but i could only do that for string

sStr := string(lList.items[i]);

But i couldn't get the float values as a := real(lList...) will result in an invalid typecast error.

So what do i do to get the float values?
Of course i have a question if that string casting will actually give me the string value. I'm not good at pointer stuff so i don't know how to do it.

+4  A: 

I'd recommend that you create a record:

TMyRecord = record
  sName: String
  x1: Double;
  x2: Double;
end;

and then create a generic list of that type:

var
  MyRecordList: TList<MyRecord>;

and from there, you should be able to easily access your data in the list.

Trying to store data in a TList with specific data types in specific positions like that is way more trouble that it needs to be.

Nick Hodges
+1. I was about to say the same thing, but Nick beat me to it. You can find the generic TList in the `Generics.Collections` unit. But it has some strange compiler quirks in Delphi 2009 and might not always work right. If you have problems with it, I'd recommend upgrading to Delphi 2010, which is a lot more stable when it comes to generics.
Mason Wheeler
+2  A: 

I agree with Nick. But you can do what you're doing anyway.

If 'a' is of type 'Real',

a := Real(aList.Items[i]^);

or if 'a' is a pointer to a Real (^Real),

a := aList.Items[i];

for strings, store the address of the first element (of course you need to test for empty strings),

s := 'Hello World';
aList.Add(@S[1]);
[...]
s1 := string(aList[i]);

or use a 'PChar' and store the address where it is pointing to,

s := 'Hello World';
aList.Add(@s^);
[...]
s1 := PChar(aList[i]);
Sertac Akyuz