|
I need to initialize an array of UDTs. For example, let's say I have a UDT, myUDT as follows:
and an Array of MyUDT called MyArray defined as MyUDT[1024]. I want to initialize all elements of MyUDT[] to some set of initial values, which are the same for all. There are many options, however the fastest and simplest seems to me to utilize the COP command to copy an instance of MyUDT called initUDT to each element as follows:
However, this doesn't work as it copies invalid data to all members of the array past element 0. There is some information available in the KB in 52154 and solution is given here in 17163. It's demonstrated that you have to use this approach to get the desired results:
I've implemented this, and it works. My question is WHY? I can't find any explanation anywhere that helps me to understand why this is necessary. Is there some sort of offset in the Memory block of an array between element 0 and element 1 that makes this necessary? |
|
What's happening in the second case is a chain reaction. First you set element 0 to a copy of initUDT. Then in the second COP instruction it's effectively doing this:
... etc. In step 2, notice that step 1 initialized MyArray[1], so it has the right data in it. In the first case, it's doing this:
... etc. 1
The key for me was understanding that the COP instruction will, by definition, iterate through the array "length" # of times. Each time offsetting both the source and destination by [# bytes of initUDT]. So as Scott describes, after the first iteration the source pointer is now pointing past the initUDT's memory space and into the memory space of some unknown or "garbage" data. I cross posted this question to mrplc.com. Here is a link to the discussion there --> http://forums.mrplc.com/index.php?showtopic=21118
(Mar 16 '11 at 19:58)
Darrin Valente
|
|
You copy command essentially is copying 3 DINTS from initUDT to the first 3 DINTS of MyArray[0] (whick works). Then it copies 3 more DINTS from whatever memory location you have below initUDT, and copies it to MyArray[1] and so on. The method that works is copying MyArray[0] to MyArray[1] MyArray[1] to MyArray[2] and so on. I have not verified this, but have run into this scenerio before! Thanks for the response. I do understand the mechanics of what is going on. What I don't understand is the underlying difference between the two methods, why the first doesn't work right and why the second does.
(Mar 11 '11 at 16:23)
Darrin Valente
|


