为什么要用结构体
如果你想表达的数据比较复杂,它不是一个值 比如你想表达日期 就有年月日三个值,如果想用一个整体去表达这么多集合在一起的数据 那么就需要用到 结构体
一个结构就是一个复合的数据类型
#include <stdio.h>
int main(int argc,char const *argv[])
{
struct date {
int month;
int day;
int year;
};
struct date toaay;
today. month = 07;
today.day = 31;
today .year = 2014;
printf( "Today's date is %i-%i-%i.\n",
today.year,today.month,today.day ) ;
return 0;
}
在函数内/外?
和本地变量—样,在函数内部声明的结构类型只能在函数内部使用
所以通常在函数外部声明结构类型,
这样就可以被多个函数所使用了
声明结构的形式
三种方法
struct point {
int x;
int y;};struct point pl, p2;pl和p2都是point 里面有x和y的值
struct {
int x;
int y;} p1,p2 ;p1 和p2都是一种无名结构,里面有x和y
struct point {
int x;
int y;} pl, p2;pl和p2都是point 里面有x和y的值
结构体的初始化
#include <stdio.h>
struct date {
int month;
int day;
int year;
};
int main(int argc, char const *argv[])
{
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. ln",
thismonth.year,thismonth.month,thismonth.day ) ;
return 0;
}
结构成员
结构和数组有点像
数组用运算符和下标访问其成员a[0] =10;
结构用.运算符和名字访问其成员
today.day 访问 today结构中的 day
p1.x 访问p1结构中的 x
结构运算
要访问整个结构,直接用结构变量的名字对于整个结构,可以做赋值、取地址,也可以传递给函数参数
pl = (struct point){5,I0};相当于pl.x= 5; pl.y = l0;
pl =p2; 相当于pl.x = p2.x; pl.y = p2.y;
数组无法做这两种运算!