PLC

Pointer

Pointers store the addresses of variables, function blocks and programs, while an application program is running. A pointer points to one of the named objects or to a variable with any data type.

Syntax:

<Identifier> : POINTER TO <Data type | Function block | Program >

Dereferencing a pointer means obtaining the value of the address to which the pointer points. You can dereference a pointer by appending the content operator to the pointer identifier, for example see pSample^ in the example below.

You can use the address operator ADR to assign the address of a variable to a pointer.

Example:

VAR
    //declaration of pointer pSample
    pSample : POINTER TO INT;
    //declaration of variables nVar1 and nVar2
    nVar1 : INT := 5;
    nVar2 : INT;
END_VAR

//pointer pSample is assigned to address of nVar1 
pSample := ADR(nVar1);

//value 5 of nVar1 is assigned to variable nVar2 by dereferencing of pointer pSample 
nVar2 := pSample^;
 
Note
If a pointer to an allocated input variable is used, the access (e.g. pTest: = ADR (input);) is interpreted as write access. This will cause a compiler warning when generating code: "...no valid assignment target".

Index access to pointers

In TwinCAT, index access [] to variables of type POINTER, STRING or WSTRING is permitted.

pint[i] returns the basic data type
Index access to pointers is arithmetic: If you use index access for a POINTER TO variable, TwinCAT calculates the offset as follows: pint[i] = (pint + i * SIZEOF (base type))^. The index access also results in implicit dereferencing of the pointer. The resulting data type is the base data type of the pointer. Note that pint[7] != (pint + 7)^!
If you use index access for a variable of type STRING, you get the character at the offset of the index expression. The result is of type BYTE. str [i] returns the i-th character of the string as SINT (ASCII).
If you use index access for a variable of type STRING, you get the character at the offset of the index expression. The result is of type WORD. wstr[i] returns the i-th character of the string as INT (Unicode).
 
Note
The result of the difference between two pointers is of type DWORD, including on 64-bit platforms, if the pointers are 64-bit pointers.
Note
Note the option of using references, which, unlike pointers, control a value directly.
Note
Note the option to monitor the memory access of pointers at runtime with the implicit monitoring function CheckPointer.

See also:

POU CheckPointer