[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 <stdio.h>
#include <malloc.h>
// Use memory across functions
// Pass the structure pointer, occupy less memory
struct Student {
int age;
int score;
char * name;
};
struct Student * createStudent (struct Student *); // Front declaration
void showStudent (struct Student *);
int main (void) {
struct Student * pst; // Definition, currently only 4 bytes
pst = createStudent (pst); // Create, allocate memory
showStudent (pst); // Show, continue to use the above memory
}
struct Student * createStudent (struct Student * pst) {
pst = (struct Student *) malloc (sizeof (struct Student)); // Allocate memory to this structure and return a pointer
pst-> age = 100; // structure member assignment
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 ===% d", pst-> name, pst-> age, pst-> score);
}