[C Language] Data Structure-preparation knowledge cross-Function Memory, data structure preparation
Memory usage across functions
When a function stops running, the memory allocated by the malloc function will not be released if free is not called.
You can continue to use this function in another function.
# Include
# Include
// Memory usage across functions
// Transmits the struct pointer, occupying less memory
Struct Student {
Int age;
Int score;
Char * name;
};
Struct Student * createStudent (struct Student *); // pre-Statement
Void showStudent (struct Student *);
Int main (void ){
Struct Student * pst; // defined. Currently, only four bytes are occupied.
Pst = createStudent (pst); // create and allocate memory
ShowStudent (pst); // display, continue to use the above memory
}
Struct Student * createStudent (struct Student * pst ){
Pst = (struct Student *) malloc (sizeof (struct Student); // allocates memory for this struct and returns a pointer
Pst-> age = 100; // assign values to struct members
Pst-> score = 9999;
Pst-> name = "taoshihan ";
Return pst;
}
Void showStudent (struct Student * pst ){
// Continue to use the memory allocated in the above function
Printf ("% s = % d", pst-> name, pst-> age, pst-> score );
}