C programming language" /> Initial values for dynamic structures
Home

 

Initial values for dynamic structures

When a variable number of instances of a structure is 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 Model = {MQMD_DEFAULT};  /* declare model instance */
    The static or auto keywords can be coded on the declaration in order 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 Instance;
    Instance = malloc(sizeof(MQMD));  /* get storage for dynamic instance */

  3. Use the memcpy function to copy the model instance to the dynamic instance:

    memcpy(Instance,&Model,sizeof(MQMD));  /* initialize dynamic instance */



 

Home