Struct in C Language

Source: Internet
Author: User

Struct in C Language

  • Struct type definition:
1 struct student2 {3    int id; 4    char name[10];5 6 };

Note: student is a custom data type, not a variable like int, char is a basic data type,

  • Struct variable definition and reference:
1 struct student 2 {3 int id; 4 char name [10]; 5} mike, lily; // directly define two struct Variables

 

1 student mike = {123, {'M', 'I', 'k', 'E'}; // define the variable and initialize 2 mike. id = 20130000 + mike. id // use 3 for (int I = 0; mike. name [I]! = '\ 0'; I ++) 4 mike. name [I] = toupper (mike. name [I]); 5 cout <"ID:" <mike. id <"name:" <mike. name <endl ;//
  • Storage of struct variables:

A struct variable occupies a continuous memory space.

  • Struct variable assignment:
1 student mike = {123, {'M', 'I', 'k', 'E'}; 2 student lily; 3 lily = mike; // you can assign values directly, the corresponding variable is also assigned a value.
  • Struct variables are used as function parameters.

The parameter is the same as the function parameter used for variable creation. When the parameter is directly passed as the parameter value, only one copy is copied, which is different from the parameter used for array name.

  • Struct variable as the return value of the Function

A copy is also used to assign values.

  • Pointer to the struct:
student mike={123,{'m','i','k','e'}};student *ps = &mike; cout<<"ID: "<<(*ps).id<<"name: " <<(*ps).name<<endl;cout<<"ID:"<<ps->id<<"name: "<<ps->name<<endl;
  • Struct array:
1 struct student 2 {3     int id;4     char name[10];5 } stu[10];

 

  • Summary: The features of struct data types are consistent with those of common data types.

 

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.