[fpc-pascal] pointer arithmetic help required

Graeme Geldenhuys graemeg.lists at gmail.com
Thu Oct 15 15:58:35 CEST 2009


Martin wrote:
> Graeme Geldenhuys wrote:
>> By the way, I am reading in the Table of Contents data for an OS/2 INF file.
>>
>>
>>   
>>>>   // now increment pEntry to point to next data structure
>>>>   // below, .Length is in bytes
>>>>   inc( pEntry, pEntry^.Length);
>>>>   
>>>>       
>>> inc(PEntry, 1)
>>>
>>> since it increments by the size of the type
>>>     
>> No, I don't think that is correct. The data pContentData is pointing at,
>> holds various structures of differing sizes. pEntry^.Length says that
>> all data relating to one TOC entry is XXX bytes in length. That means
>> the TTOCEntryStart structure itself (only 3 bytes) and various other
>> structures making up the difference.
>>   
> If pentry differs in length, then use a byte pointer, (for which inc 
> will work in bytes), and cast it onlt when you access the data.


Ah, I get it now! :-) Because pEntry is a pointer to a structure, inc()
will increment pEntry by multiples of the structure size. Casting it to
a PByte forces inc() to increment in bytes, which is what pEntry^.Length
is indicating.  There is light at the end of this long tunnel. Thanks
for your help, Martin.

I changed the code at the end of the loop to the following. Now stepping
through the code, it's pulling out the data correctly. :-)

    p := PByte(pEntry);
    inc(p, pEntry^.Length);
    pEntry := pTTOCentryStart(p);


Now I know why vendors of newer languages (Dephi, Java etc) are trying
to hide pointers from programmers. They are very tricky to work with -
and give errors without warning!

Regards,
  - Graeme -




More information about the fpc-pascal mailing list