Concept
How do you dynamically allocate and initialize a structure?
ComputerScienceOne / Selection Operators
"Student *s = (Student *) malloc(sizeof(Student) * 1); The multiplication by 1 in this example is not strictly necessary, but emphasizes the fact that we are allocating space for one structure and not an array of structures. Initializing a dynamically allocated structure like this does not initialize any of its variables as there are no default values defined by C. Moreover, it does not initialize memory for any pointer member variables. For example the firstName and lastName pointers need to be manually initialized with additional malloc() calls."
Related Ideas
- How can structures be dynamically allocated?ComputerScienceOne · Declaration & Initialization
- How do you access members through a pointer to a structure?ComputerScienceOne · Selection Operators
- How can factory functions simplify the creation of structure instances?ComputerScienceOne · Factory Functions
- How are structure instances declared and initialized?ComputerScienceOne · Declaration & Initialization
- What other memory allocation functions and pointer cast options does C provide?ComputerScienceOne · Dynamic Memory
- How do you use and validate a dynamically allocated array?ComputerScienceOne · Dynamic Memory
- How does malloc() allocate memory for a dynamic array?ComputerScienceOne · Dynamic Memory
- How can one structure be composed of another structure?ComputerScienceOne · Declaration & Initialization