输出:
Enter today's date(mm dd yyyy):12 31 2014 Tomorrow's date is 2015-1-1. Program ended with exit code: 0
指向结构的指针
struct date {
int month;
int day;
int year;
} myday;
struct date *p = &myday;
(*p).month = 12;
p->month = 12;
* 用->表示指针所指向的结构变量中的成员
// // main.c // structure // // Created by liuxinming on 15/4/12. // Copyright (c) 2015年 liuxinming. All rights reserved. // #includestruct point { int x; int y; }; struct point* getStruct(struct point*); void output(struct point); void print(const struct point *p); int main(int argc, const char * argv[]) { struct point y = {0, 0}; getStruct(&y); output(y); output(*getStruct(&y)); print(getStruct(&y)); return 0; } struct point* getStruct(struct point *p){ scanf(%d, &p->x); scanf(%d, &p->y); printf(%d, %d , p->x, p->y); return p; } void output(struct point p){ printf(%d, %d ,p.x, p.y); } void print(const struct point *p){ printf(%d, %d,p->x, p->y); }
输出:
10 50 10, 50 10, 50
结构数组
struct date dates[100];
struct date dates[] = {
{4,5,2005},
{2,4,2005}
};
案例:
// // main.c // structure // // Created by liuxinming on 15/4/12. // Copyright (c) 2015年 liuxinming. All rights reserved. // #includestruct time{ int hour; int minutes; int seconds; }; struct time timeUpdate(struct time now); int main(void) { struct time testTime[5] = { {11,59,59}, {12,0,0}, {1,29,29}, {23,59,59}, {19,12,27} }; int i; for (i = 0; i < 5; i++) { printf(Time is %.2i:%.2i:%.2i , testTime[i].hour,testTime[i].minutes, testTime[i].seconds); testTime[i] = timeUpdate(testTime[i]); printf(... one second later it's %.2i:%.2i:%.2i , testTime[i].hour,testTime[i].minutes, testTime[i].seconds); } return 0; } struct time timeUpdate(struct time now){ ++ now.seconds; if( now.seconds == 60){ now.seconds = 0; ++ now.minutes; if (now.minutes == 60){ now.minutes = 0; ++ now.hour; if(now.hour == 24){ now.hour = 0; } } } return now; }
Time is 11:59:59 ... one second later it's 12:00:00 Time is 12:00:00 ... one second later it's 12:00:01 Time is 01:29:29 ... one second later it's 01:29:30 Time is 23:59:59 ... one second later it's 00:00:00 Time is 19:12:27 ... one second later it's 19:12:28 Program ended with exit code: 0
结构中的结构
struct dateAndTime{
struct date sdate;
struct time stime;
}
嵌套的结构
struct rectangle{
struct point pt1;
struct point pt2;
};
//如果有变量
struct rectangle r;
//就可以有:
r.pt1.x = 1;
r.pt1.y = 2;
r.pt2.x = 11;
r.pt2.y = 22;
//如果有变量定义
struct rectangle *rp;
rp = &r;
//那么这四种形式是等价的
//r.pt1.x , rp->pt1.x, (r.pt1).x, (rp->pt1).x
//但是没有rp->pt1->x 因为pt1不是指针