Initial values for dynamic structures
When a variable number of instances of a structure is required, the instances are typically created in main storage obtained dynamically using the calloc or malloc functions. To initialize the fields in such structures, consider the following technique:
- 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. - 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 */
- Use the memcpy function to copy the model instance to the dynamic instance:
memcpy(Instance,&Model,sizeof(MQMD)); /* initialize dynamic instance */
Parent topic: C programming