目的:将不同类型的数据组合成一个有机整体
定义:
形式1
struct point{
int x;
int y;
};
struct point p1,p2;
形式2
struct point{
int x;
int y;
}p1,p2;
形式3
struct {
int x;
int y;
}p1,p2;
初始化:给结构体赋初值
#include<stdio.h>
int main() {
struct point {
int x;
int y;
}p2;
struct point p1 = {1,3};
p2.x = 2;
p2.y = 4;
struct point p3 = {5};
printf("%d,%d\n", p1.x, p1.y);
printf("%d,%d\n", p2.x, p2.y);
printf("%d,%d", p3.x, p3.y);
return 0;
}
结构与函数
函数接收、返回的是结构体的值
#include <stdio.h>
struct point {
int x;
int y;
};
struct point getstruct(void);//结构体作为函数的返回值
void output(struct point q);//结构体作为函数的接收值
int main(int argc, char **argv) {
struct point y ={0,0};
output(y);
y=getstruct();
output(y);
}
struct point getstruct(void){
struct point p;
scanf("%d",&p.x);
scanf("%d",&p.y);
return p;
}
void output(struct point q){
printf("%d,%d",q.x,q.y);
}
指向结构的指针
If a large structure is to be passed to a function,it is generally more eficient to paa a pointer than to copy the whole structure.——K&R(p.131)
传递指针比传递结构更加高效
struct point *p= &p1;
p1.x=0;
(*p).x=0;
p->x=0;//p所指的x;这三种等价,用->表示指针所指的结构变量中的成员
#include <stdio.h>
struct point {
int x;
int y;
};
void getstruct(struct point *p); //结构体指针作为函数的接收值
void output(const struct point *q); //结构体指针作为函数的接收值
int main(int argc, char **argv) {
struct point y = {0, 0};
output(&y);
getstruct(&y);
output(&y);
return 0;
}
void getstruct(struct point *p) {
scanf("%d", &p->x); //p->x相当于(*p).x
scanf("%d", &p->y); //相当于(*p).y
}
void output(const struct point *q) {
printf("%d,%d", q->x, q->y);
}
数组与结构
数组 | 结构 |
---|---|
专卖店:单元的类型必须一致 | 大商场:各成员类型可不同 |
a[0];用[] 下标访问单元 | today.day;用. 名字访问成员 |
变量本身a是指针 | 变量本身不是指针 |