Defines the use of struct variables, struct Variables

Source: Internet
Author: User

Defines the use of struct variables, struct Variables
(1) define struct types

1. A user-created data structure composed of different types of data is called a struct.
For example:
Struct Date
{Int month;
Int day;
Int year;
};
Struct Student
{Int num;
Char name [20];
Char sex;
Int age;
Struct Date birthday;
Char addr [20];
};
The members in the struct can belong to another struct type, for example, birthday in the preceding example.
This only creates a struct type and does not define variables, so the system does not allocate storage units to it.

(2) define struct type variables

(1) Declare the type before defining the variable
Struct Student student1, student2;
(2) Declare types and define variables at the same time
Struct Student {
Int num;
Char name [20];
.............
} Student1, student2;

(3) initialization and reference of struct Variables

Initialization example:

 1 #include<stdio.h> 2 int main(){ 3     struct Student{ 4         long int num; 5         char name[20]; 6         char sex; 7         char addr[20]; 8     }a={1001,"Li",'M',"BeiJing"}; 9     printf("name:%s\naddress:%s\n",a.name,a.addr);10 } 

Struct variables of the same type can be assigned values to each other, for example, student1 = student2.

Example:

1 # include <stdio. h> 2 int main () {3 struct student {4 int num; 5 char name [20]; 6} student1; 7 scanf ("% d % s", & student1.num, student1.name); 8 printf ("student ID: % d \ n name: % s \ n", student1.num, student1.name); 9}

Note: scanf has a value character when inputting num, but no value when inputting name. This is because the array name itself represents the address.

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.