Initial values for dynamic structures

 

When a variable number of instances of a structure are required, the instances are usually created in main storage obtained dynamically using the calloc or malloc functions.

To initialize the fields in such structures, the following technique is recommended:

  1. Declare an instance of the structure using the appropriate MQxxx_DEFAULT macro variable to initialize the structure. This instance becomes the model for other instances:
    MQMD ModelMsgDesc = {MQMD_DEFAULT};
                                      /* declare model instance */
    Code the static or auto keywords on the declaration to give the model instance static or dynamic lifetime, as required.

  2. Use the calloc or malloc functions to obtain storage for a dynamic instance of the structure:
    PMQMD InstancePtr;
    InstancePtr = malloc(sizeof(MQMD));
                                      /* get storage for dynamic instance */

  3. Use the memcpy function to copy the model instance to the dynamic instance:
    memcpy(InstancePtr,&ModelMsgDesc,sizeof(MQMD));
                                      /* initialize dynamic instance */

 

Parent topic:

Coding in C


fg11710_