[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

# 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 );

}

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.