Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!uwm.edu!bionet!agate!ucbvax!bloom-beacon!eru!hagbard!sunic!lth.se!newsuser From: sundinKC@dna.lth.se (Anders Sundin) Newsgroups: comp.sys.mac.programmer Subject: Re: Variable length arrays in Pascal--can it be done? Message-ID: <1991Apr3.075436.22107@lth.se> Date: 3 Apr 91 07:54:36 GMT References: <1521@babcock.cerc.wvu.wvnet.edu> Sender: newsuser@lth.se (LTH network news server) Organization: Lund University Computing Center, Sweden Lines: 89 Kurisuto writes: > I want to have variable length arrays in Pascal. Pascal, however, > does not want me to have variable length arrays in it. I think I've > figured out a way to do this. This solution is probably glaringly > obvious to more experienced programmers, but I want to run it > past you to see if there's any reason why it shouldn't work. > > Suppose I define a type in Pascal which is an arbitrarily large > array: say, one with 10000 elements in it, or some number larger than > I will ever need. Suppose I then define a pointer to point to > this type, and a handle to point to the pointer. Let's say I want > to start out with seven elements in the array, so I use NewHandle > and allocate just enough memory to hold those seven elements. I > store this number seven in a variable to keep track of how big > the array is. > > Now, as long as I am careful not to refer to any elements beyond the > end of the memory block, I should not have any problems, right? > And if I want to resize the array, I can use SetHandleSize, > making sure to keep track of how many elements are now in the array, > right? Is there any reason why this shouldn't work? Here is how I do dynamic memory allocation in Pascal. data = record x : Real; y : Real; z : Real; end; arrHandle = ^arrPtr; arrPtr = ^arr; arr = array [1..MaxInt] of data; objHandle = ^objPtr; objPtr = ^obj; obj = record nData : Integer; nAlloc : Integer; dataH : arrHandle; nextObj : objHandle; end; function AllocObject(n: LongInt): objHandle; var theObj : objHandle; begin theObj := objHandle(NewHandle(SizeOf(obj))); if theObj <> nil then begin theObj^^.dataH := arrHandle(NewHandle(n * SizeOf(data))); if theObj^^.dataH = nil then begin DisposHandle( Handle(theObj)); theObj := nil; end else begin theObj^^.nData := 0; theObj^^.nAlloc := n; theObj^^.nextObj := nil; end; end; AllocObject := theObj; end; function ReallocObject(theObj: objHandle; n: LongInt): Boolean; begin SetHandleSize(Handle(theObj^^.dataH), n * SizeOf(data)); if MemError = noErr then begin theObj^^.nAlloc := n; if theObj^^.nData > n then theObj^^.nData := n; ReallocObject := true; end else ReallocObject := false; end; -- Anders Sundin e-mail: sundinKC@dna.lth.se Organic Chemistry 2, ok2aps@seldc52.bitnet P.O. Box 124 phone: +46 46 108214 S-22100 Lund, Sweden fax: +46 46 108209