C primer plus: Use pointers in the structure, use malloc to allocate pointer space and free

Source: Internet
Author: User

// C primer plus
// Use Pointer in Structure
// Allocate memory space to pointers in the Structure
// Free releases the previously allocated memory space
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>

# Include "tsong. H"

Struct namect {
Char * fname;
Char * lname;
Int letters;
};

Void getinfo (struct namect *); // enter the name
Void makeinfo (struct namect *); // calculates the length.
Void showinfo (const struct namect *); // print the information in the Structure
Void cleanup (struct namect *); // release memory

Int main (){
Struct namect person;
Getinfo (& person );
Makeinfo (& person );
Showinfo (& person );
Cleanup (& person );

Return 0;

}
Void getinfo (struct namect * PST)
{
Char temp [81];
Puts ("Please enter your first name ");
Gets (temp );
PST-> fname = (char *) malloc (strlen (temp) + 1 );
Strcpy (PSt-> fname, temp );
Puts ("Please enter your last name ");
Gets (temp );
PST-> lname = (char *) malloc (strlen (temp) + 1 );
Strcpy (PSt-> lname, temp );
}

Void makeinfo (struct namect * PST)
{
PST-> letters = strlen (PSt-> fname) + strlen (PSt-> lname );
}

Void showinfo (const struct namect * PST)
{
Printf ("% S % s, your name contains % d letters \ n", PSt-> fname, PSt-> lname, PSt-> letters );
}

Void cleanup (struct namect * PST)
{
Free (PSt-> fname );
Free (PSt-> lname );
}

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.