0

In my project I have a type like:

TYPE myDataStruct :
STRUCT
    A : UINT;
    B : WORD;
    C : REAL;
    D : Custom_Obj;
END_STRUCT
END_TYPE

And I need to keep an array of this type for persistent memory. I can't just use VAR RETAIN because this particular piece of memory needs to persist through a download. The controller I am using has a way to do this but in order for it to work I need to be able to set the array equal to an initial value. So if I have declared

myarray := ARRAY[0..20] OF myDataStruct;

How do I then initialize this array to a blank array? What is the equivalent of new in other languages?

I have guessed

myarray := [21(A := 0,
               B := '',
               C := 0.0,
               D := ??? )];

But that doesn't appear to be right. It could be simplified if there were only one level deep of custom structs and for this application I could do that. However, I still don't think I have the syntax right.

1
  • Did you get your answer? Commented Feb 3, 2019 at 4:19

2 Answers 2

2

What is the equivalent of new in other languages?

The analog of this is

VAR
    EmptyArray  : ARRAY[0..20] OF myDataStruct;
END_VAR

If you want to pre-populate it with default values

VAR
    EmptyArray  : ARRAY[0..20] OF myDataStruct := [
        (A := 100, B := 200, С := 0.0, D := ???),
        (A := 34, B := 45, С := 0.1, D := ???),
        ..... etc
    ];
END_VAR

For CoDeSys 2.3 delete [ and ].

What you have to understand that EmptyArray is not a prototype of data you need but already initialized variable.

Sign up to request clarification or add additional context in comments.

Comments

1

There is no way to initialize it in "x = new struct()" way. You also can't assign the whole array in the code with something like myarray = [1, 2, 3] etc, as far as I know.

If you just want to set it empty with values like 0, '', etc, then there are two ways that I would use:

1. Use MEMSET function to set all bytes to 0

Link to the online help

//Something like
MemSet(
    pbyBuffer   := ADR(myarray),    //Address of the variable
    byValue     := 0,               //Byte that address is filled with
    dwSize      := SIZEOF(myarray)  //How many bytes? (variable size)
)

2. Create a dummy variable and assign it to the myarray

The variable is always initialized to zeros, so EmptyArray values are all 0/empty etc.

VAR
    EmptyArray  : ARRAY[0..20] OF myDataStruct;
END_VAR

//In the code
myarray := EmptyArray;

I hope I understood your question correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.