Mega Code Archive

 
Categories / Delphi / Ide Indy
 

How to do pointer arithmetic in Delphi

Title: How to do pointer arithmetic in Delphi? Question: How to do pointer arithmetic in Delphi? Answer: First a brief explanation of pointer arithmetic. When you are dealing with dynamic memory locations and all you have is a pointer to where it all begins, you want to have the ability to traverse that line of memory to be able to perform whatever functions you have in mind for that data. This can be accomplished by changing the place in memory where the pointer points. This is called pointer arithmetic. The main idea that must be kept in mind when doing your pointer arithmetic is that you must increment the pointer's value by the correct amount. The correct amount is determined by the size of the object receiving the pointer and the Delphi version. e.g. char = 1 byte; integer = 2 bytes (16 bit version); double = 8 bytes (16 bit version); etc. The Inc() and Dec() functions will alter the amount by the correct amount. (The compiler knows what the correct size is.) If you are doing dynamic memory allocation, it is done like this: procedure TestIt; var MyArray: array[0..30] of char; b: ^char; i: integer; begin StrCopy(MyArray, 'Delphi forever!'); {get something to point to} b := @MyArray; { assign the pointer to the memory location } for i := StrLen(MyArray) downto 0 do begin write(b^); { write out the char at the current pointer location. } inc(b); { point to the next byte in memory } end; end; Remember, if you want to test the function above you have to make a console application. The following code demonstrates that the Inc() and Dec() functions will increment or decrement accordingly by size of the type the pointer points to: var P1, P2 : ^LongInt; L : LongInt; begin P1 := @L; { assign both pointers to the same place } P2 := @L; Inc(P2); { Increment one } { Here we get the difference between the offset values of the two pointers. Since we originally pointed to the same place in memory, the result will tell us how much of a change occured when we called Inc(). } L := Ofs(P2^) - Ofs(P1^); { L = 4; i.e. sizeof(longInt) } end; You can change the type to which P1 and P2 point to something other than a longint to see that the change is always the correct value (SizeOf(P1^)).