一、结构体
1.1、类型定义(typedef)
typedef用来给数据类型取新的名字。
示例:
#include <iostream>
using namespace std;
int main() {
typedef int MYINT;
MYINT a = 0;
printf("%d\n",a);
typedef char MYCHAR;
MYCHAR b = 'A';
printf("%c\n",b);
return 0;
}
输出结果:
0
A
1.2、结构体
示例:
#include <iostream>
using namespace std;
int main() {
struct {int x;int y;} point;
point.x = 10;
point.y = 15;
printf("%d,%d",point.x,point.y);
return 0;
}
输出结果:
10,15
使用typedef给结构体命名。
示例2:
#include <iostream>
using namespace std;
typedef struct {
int x;
int y;
} Point;
int main() {
Point point;
point.x = 10;
point.y = 15;
printf("%d,%d",point.x,point.y);
return 0;
}
输出结果:
10,15
不使用typedef也可以给结构体命名。
示例3:
#include <iostream>
using namespace std;
struct Point{
int x;
int y;
} ;
int main() {
struct Point point;
point.x = 10;
point.y = 15;
printf("%d,%d",point.x,point.y);
return 0;
}
输出结果:
10,15
1.3、指向结构体的指针
使用指针取出结构体的变量,不能使用.来取,而是使用->来取变量。
示例:
#include <iostream>
using namespace std;
typedef struct {
int x;
int y;
} Point;
int main() {
Point point;
Point *p;
p = &point;
p->x = 10;
p->y = 15;
printf("%d,%d",p->x,p->y);
return 0;
}
输出结果:
10,15
1.4、自引用结构
示例:
#include <iostream>
using namespace std;
typedef struct Point {
int x;
int y;
struct Point* next;
} Point;
int main() {
Point p1,p2,p3,p4,p5;
Point *p;
p1.x = 1;p1.y = 0;
p2.x = 4;p2.y = 1;
p3.x = 2;p3.y = 4;
p4.x = 3;p4.y = 2;
p5.x = 1;p5.y = 6;
p1.next = &p2;
p2.next = &p3;
p3.next = &p4;
p4.next = &p5;
p5.next = NULL;
for (p = &p1;p!=NULL;p=p->next)
printf("(%d,%d)\n",p->x,p->y);
return 0;
}
输出结果:
(1,0)
(4,1)
(2,4)
(3,2)
(1,6)
我的微信公众号.jpg
网友评论