Translating C pointer code example to Delphi pointer syntax
Question
I am working with a binary file structure. The code example for reading the data is in C, and I need to read it in Delphi. I hasten to add I have no C programming experience.
Given the following
typedef struct {
uchar ID, DataSource;
ushort ChecksumOffset;
uchar Spare, NDataTypes;
ushort Offset [256];
} HeaderType;
...
typedef struct {
ushort ID;
...
ushort DistanceToBin1Middle,TransmitLength;
} FixLeaderType;
...
HeaderType *HdrPtr;
FixLeaderType *FLdrPtr;
unsigned char RcvBuff[8192];
void DecodeBBensemble( void )
{
unsigned short i, *IDptr, ID;
FLdrPtr = (FixLeaderType *)&RcvBuff [ HdrPtr->Offset[0] ];
if (FLdrPtr->NBins > 128)
FLdrPtr->NBins = 32;
...
The bit I am having difficulty following is this:
FLdrPtr = (FixLeaderType *)&RcvBuff [ HdrPtr->Offset[0] ];
From the little I understand, [ HdrPtr->Offset[0] ];
would be returning the value of the first Offset array item from the HeaderType struct pointed to by HdrPtr? So equivalent to HdrPtr^.Offset[0]
?
Then &RcvBuff [ HdrPtr->Offset[0] ];
should be returning the memory address containing the value of the RcvBuff array item indexed, so equivalent to @RecBuff[HdrPtr^.Offset[0]]
?
Then I get lost with (FixLeaderType *)..
. Could someone please help explain exactly what is being referenced by FldrPtr ?
Solution
The bits of code that are relevant are
FixLeaderType *FLdrPtr;
unsigned char RcvBuff[8192];
FLdrPtr = (FixLeaderType *)&RcvBuff [ HdrPtr->Offset[0] ];
FldPtr
is of typeFixLeaderType *
, or pointer toFixLeaderType
.RcvBuff
is an array ofchar
.HdrPtr->Offset[0]
resolves to an ushort value, soRcvBuff [ HdrPtr->Offset[0] ]
yields achar
value.- The
&
means that instead of getting the value of thechar
the address of the value is returned. Note that this means that it is of typechar *
. - The
char *
type is the wrong type to assign toFldPtr
. The(FixLeaderType *)
converts the type so that it is valid. This is called a cast operation.
OTHER TIPS
i think you should read those like:
* = pointer to
& = address of
that makes things a lot easier