C语言之结构"
一、声明结构类型
#include <stdio.h>
int main()
{
struct date {
int month;
int day;
int year;
};//分号不能丢
struct date today;
today.month=07;
today.day=31;
today.year=2014;
printf("today's date is %i-%i-%i.\n",today.month,today.day,today.year);
return 0;
}
注:1.和本地变量一样,在函数内部声明的结构类型只能在函数内部使用
二、声明结构的形式
struct point {
int x;
int y;
};
struct point p1,p2;
//p1和p2都是point,里面有x和y的值
struct{
int x;
int y;
}p1,p2;
//p1和p2都是一种无名结构,里面有x和y
struct point {
int x;
int y;
}p1,p2;
//p1和p2都是point,里面有x和y的值
//tips:对于第一和第三种形式,都声明了结构point,第二种只定义了两个变量,没有声明结构名
//结构的初始化
#include <stdio.h>
struct date
{
int month;
int day;
int year;
};
int main()
{
struct date today = { 07, 31, 2014 };
struct date thismonth = { .month = 7, .year = 2014 };
printf("today's date is %i-%i-%i.\n", today.year, today.month, today.day);
printf("this month is %i-%i-%i.\n", thismonth.year, thismonth.month, thismonth.day);
return 0;
}