Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Assigned() with a dynamic array.

Status
Not open for further replies.

surjay

Programmer
Jun 11, 2009
2
US
A simple function example:

begin
if not Assigned(FArray[AIndex]) then
FArray[AIndex] := CreateItem(AIndex);

Result := FArray[AIndex];
end;


where FArray is a dynamic array of objects. It seems that Assigned() doesn't work well here. For example, when Length(FArray) = 1, Assigned(FArray[1]) = True, Assigned(FArray[198]) = True, and so on. Some indexes return true, some false.

I assume this just has to do with the nature of a dynamic array in the first place, so I'm wondering if there's a different way to use Assigned() in this case, or a different command. I know workarounds like checking something about that index's specific object, etc., but I'm mainly looking for a better understanding of Assigned() in this case and something directly related to it.

Thanks.
 
if you are working with dynamic arrays that contain objects, why not use a TObjectList instead?

/Daddy

-----------------------------------------------------
What You See Is What You Get
Never underestimate tha powah of tha google!
 
It is generally not a good idea to access array-elements that are behind the allocated size of the array. If, like in your example, your array has a lenght of 1, then you should never access elements with an index bigger than 0.
Compile your Project with the comoiler-option "Range checking" set. Next time you step over the Assigned()-statement, it will generate an exception, if the index is too big.

The Assigned()-function just receives a Pointer-Argument which is checked for nil. If Range-checking is disabled, accessing an element behind an object-array´s length means just reading 4 Bytes of memory from the heap, somewhere behind the array. These Bytes are interpreted as a pointer. This Pointer may or may not be nil, since the memory, it was read from, might be in use for storing anything else.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top