A pointer stores the memory address of objects, such as variables or function block instances, at runtime.
Syntax of the pointer declaration:
<pointer name>: POINTER TO <data type | data unit type | function block>;
Example
FUNCTION_BLOCK FB_Point VAR piNumber: POINTER TO INT; iNumber1: INT := 5; iNumber2: INT; END_VAR piNumber := ADR(iNumber1); // piNumber is assigned to address of iNumber1 iNumber2 := piNumber^; // value 5 of iNumber1 is assigned to variable iNumber2 by dereferencing of pointer piNumber
Dereferencing a pointer means obtaining the value to which the pointer points. A pointer
is dereferenced by appending the content operator ^
to the pointer identifier (for example, piNumber^
in the example above). To assign the address of an object to a pointer, the address
operator ADR
is applied to the object: ADR(iNumber1)
.
In online mode, you can click “Edit Browse Go to Reference” to jump from a pointer to the declaration location of the referenced variable.




NOTICE

When a pointer points to an I/O input, write access applies. This leads to the compiler warning “'<pointer name >' is not a valid assignment target” when the code is generated. Example: pwInput := ADR(wInput);
If you require a construct of this kind, you have to first copy the input value (wInput
) to a variable with write access.
Index access to pointers
CODESYS permits the index access []
to variables of type POINTER TO
, as well as to the data types STRING
or WSTRING
.
The data, which the pointer points to, can also be accessed by appending the bracket
operator []
to the pointer identifier(for example, piData[i]
). The base data type of the pointer determines the data type and the size of the
indexed component. In this case, the index access to the pointer is done arithmetically
by adding the index dependent offset i * SIZEOF( <base type> )
to the address of the pointer. The pointer is dereferenced implicitly at the same
time.
Calculation: piData[i] := (piData + i * SIZEOF(INT))^;
This is not: piData[i] != (piData + i)^
.
Index access STRING
When you use the index access with a variable of the type STRING
, you get the character at the offset of the index expression. The result is of type
BYTE
. For example, sData[i]
returns the i-th character of the character string sData
as SINT
(ASCII).
Index access WSTRING
When you use the index access with a variable of the type WSTRING
, you get the character at the offset of the index expression. The result is of type
WORD
. For example, wsData[i]
returns the i-th character of the character string as INT
(Unicode).
Subtracting pointers
The result of the difference between two pointers is a value of type DWORD
, even on 64-bit platforms when the pointers are 64-bit pointers.
Using references provides the advantage of guaranteeing type safety. That is not the case with pointers.
The memory access of pointers can be checked at runtime by the implicit monitoring
function CheckPointer
.