A comparison between structure array and the application of malloc to structural body space

Source: Internet
Author: User

A comparison between structure array and the application of malloc to structural body space

  The title of the article sounds very awkward, perhaps I describe the less clear, or to see the routine it:

I'll start with the first malloc I'll ever use:

  

1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5 structStudent6 {7     Char*name;8     intAge ;9 };Ten  One intMain () A { -     structStudent *p_student=NULL; -P_student= ((structStudent *)malloc(sizeof(struct( Student) )); the  -P_student->name="Tom"; -P_student->age= at; -  +printf"name:%s\n",p_student->name); -printf"age:%d\n",p_student->Age ); +  A      Free(p_student);
p_student=null;//Note that the malloc space is released, but the struct pointer still exists and still needs to point to NULL; - return 0; -}

  The above procedure is simple and clear, is to apply for a structure pointer, and then open up a memory space, ready to store "struct student" type of variable data, variables are initialized, print out, finally release malloc space.

Here's another structure array:

1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5 structStudent6 {7     Char*name;8     intAge ;9 };Ten  One intMain () A { -     structStudent p_student[sizeof(structStudent)]={"Tom", at}; -  theprintf"name:%s\n",p_student->name); -printf"age:%d\n",p_student->Age ); -     return 0; -}

  This is the structure of the array, that is: "struct student" type of array "P_student", the space size of "sizeof (struct student)", when initialized, directly behind the writing on the line.

  From the above two examples, I found that the second structure of the array is useful.

A comparison between structure array and the application of malloc to structural body space

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.