Replicating Pointer Fields in Structures

QUESTION: I need a pointer field in a structure. But when I replicate that structure to make an array of structures, I find that all of the pointer fields point to the same pointer variable. Here is an example of what I mean.

   IDL> struct = { ptr:Ptr_New(/ALLOCATE_HEAP), data:5 }
   IDL> array = Replicate(struct, 10)    IDL> *array[3].ptr = Indgen(10)
   IDL> Print, *array[7].ptr
       0       1       2       3       4       5       6       7       8       9

Each pointer points to the same variable!! How can I initialize this pointer field in my structure so that each pointer points to a different pointer variable, which, of course, is what I want?

ANSWER: Yes, I can see that is a problem. The solution is to initialize your pointer field after you replicate your structure. The proper way to set this up is like this.

    IDL> struct = { ptr:Ptr_New(), data:5 }
   IDL> array = Replicate(struct, 10)
   IDL> array.ptr = PtrArr(10, /ALLOCATE_HEAP)
   IDL> *array[3].ptr = Indgen(10)    IDL> Help, *array[7].ptr
       <PtrHeapVar770> UNDEFINED = <Undefined> 

Now, each pointer reference is to a different pointer variable and can be set independently.

Version of IDL used to prepare this article: IDL 7.1.2

Google
 
Web Coyote's Guide to IDL Programming