Learning point C language (24): Data Type-structure (struct)

Source: Internet
Author: User
1. The structure is a set of multiple variables:
 
# Include <stdio. h> int main (void) {struct rec {int X; int y ;}; struct rec R1; r1.x = 111; r1.y = 222; printf ("% d, % d ", r1.x, r1.y); getchar (); Return 0 ;}

  

2. Declare variables at the same time during definition:

 
# Include <stdio. h> int main (void) {struct rec {int X, Y;} R1, R2; r1.x = 111; r1.y = 222; r2.x = 333; r2.y = 444; printf ("% d, % d \ n", r1.x, r1.y); printf ("% d, % d \ n", r2.x, r2.y); getchar (); return 0 ;}

  

3. Declare variables and assign values when defining them:

 
# Include <stdio. h> int main (void) {struct rec {int X, Y;} R1 = {777,888}; printf ("% d, % d \ n", r1.x, r1.y ); getchar (); Return 0 ;}

  
# Include <stdio. h> int main (void) {struct rec {char name [12]; short age;} R1 = {"zhangsan", 12}; printf ("% s, % u ", r1.name, r1.age); getchar (); Return 0 ;}

  

4. The declared variable is the initial value assigned:

 
# Include <stdio. h> int main (void) {struct rec {char name [12]; short age ;}; struct rec R1 = {"zhangsan", 12}; printf ("% s, % u ", r1.name, r1.age); getchar (); Return 0 ;}

  

5. assigning values to strings after declaration is troublesome:

 
# Include <stdio. h> # include <string. h> int main (void) {struct rec {char name [12]; short age ;}; struct rec R1; strcpy (r1.name, "zhangsan"); r1.age = 18; printf ("% s, % u", r1.name, r1.age); getchar (); Return 0 ;}

  

6. If you declare variables directly during definition, You can omit the structure Name:

 
# Include <stdio. h> int main (void) {struct {char name [12]; short age;} R1 = {"zhangsan", 12}; printf ("% s, % u ", r1.name, r1.age); getchar (); Return 0 ;}

  

7. assign values through scanf:

 
# Include <stdio. h> int main (void) {struct rec {char name [12]; short age;} R1; printf ("name:"); scanf ("% s ", r1.name); printf ("Age:"); scanf ("% d", & r1.age); printf ("Name: % s; age: % d", r1.name, r1.age); getchar (); Return 0 ;}

  

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.