[C Language] Data Structure-preparation knowledge cross-Function Memory, data structure preparation

Source: Internet
Author: User

[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);
} 

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.