Concept

How are structure instances declared and initialized?

ComputerScienceOne / Declaration & Initialization

"Once we have defined a structure (and included the header file it has been defined in), we can create instances using the usual syntax.\n\nStudent s;\n\nStudent t;\n\nThese static declarations will allocate enough space on the stack to hold all of the data associated with the structures (the two char * pointers, int, and double and the three int variables in the Date structure). However, the values stored in each of the structure’s member variables are undefined. With this style of declaration, C does not define default values.\n\nAnother way to declare instances of our structures is to use the following syntax.\n\nStudent s = {};\n\nStudent t = {\n\n12345678,\n\n\"Grace\",\n\n\"Hopper\",\n\n4.0,\n\n{\n\n1906,\n\n1,\n\n1\n\n}\n\n};\n\nThe first declaration creates a Student structure with default values (zero for any numeric types, null for any pointers). The second creates a Student structure initialized with the values provided in the curly brackets. The order matters here and will match the ordering of the original structure declaration. Since the dateOfBirth is a structure itself, a nested set of values within curly brackets is necessary. One draw back to this type of declaration is that the character pointers are statically declared. The strings \"Grace\" and \"Hopper\" are initialized in a read-only segment of memory, any attempts to change the contents of these strings are undefined behavior. The pointers themselves, however, can be reassigned.\n\nThis static declaration allocates the structure on the stack. Since structures consist of multiple pieces of data, their memory footprint is larger. Allocating larger and larger structures on the stack runs the risk of running out of stack memory resulting in a stack overflow."

Related Ideas

How are structure instances declared and initialized? | ComputerScienceOne | Bifalgorithm | Bifalgorithm