C语言程序设计 学习笔记 结构、类型定义

结构体基本

struct structname {
	//自行定义
};//分号不要忘了

指向结构的指针:

struct date{
	int month;
	int year;
	int day;
} myday;
date *p = &myday;
//赋值:
(*p).month = 2;
//更简便的方式:
p->month = 2;

用例:指针参数

struct point* getStruct(struct point *p){//struct point*指的返回一个指针类型
	scanf("%d",&p->x);
	scanf("%d",&p->y);
	printf("%d %d",p->x,p->y);
	return p;
}
int main(){
	point y;
	getStruct(y);
	*getStruct(y) = (struct point){1,2};//相当于对返回过来的*p再赋值
}

结构中的结构

struct dateAndTime{
	struct date stime;
	struct tiem stime;
};

struct point{
	int x;
	int y;
};
struct rectangle{
	struct point pt1;
	struct point pt2;
};
//如果有变量
	struct rectangle r;
//就可以有:
	//r.pt1.x、r.pt1.y、r.pt2.x和r.pt2.y	

如果有变量定义:

struct rectangle r,*rp;
re = &r;

那么下面的四种形式是等价的:

r.pt1.x
rp->pt1.x
(r.pt1).x
(rp->pt1).x

但是没有rp->pt1->x(因为pt1不是指针)

类型定义
typeof 原类型 自定义类型名;
例:

typeof int Length;//Length等价于int
typeof *char[10] Strings;//用Strings表示有10个字符串的数组
typeof struct node{
	int data;
	struct node *next;
}aNode;
或
typedef struct node aNode;//这样用aNode可以代替struct node

猜你喜欢

转载自blog.csdn.net/a656418zz/article/details/83869855
今日推荐