2.8.1结构体的定义
定义一个结构体的基本格式如下:
struct Name{
};
eg:
struct studentInfo {
intid;
char gender;
char name [20] ;
char major [20] ;
}Alice, Bob, stu[1000] ;
studentInfo是这个结构体的名字,
而在大括号外定义了studentInfo型的Alice和Bob代表两个结构体变量;
之后的stu[1000]就是当有很多学生时定义的一个结构体数组
(如果不在此处定义变量或数组,则大括号外直接跟上分号)。
定义结构体变量和结构体数组除了可以像上面直接定义外,
也可以按照基本数据类型(如int型)那样定义:
studentInfoAlice;
studentInfostu[1000] ;
虽然不能定义自己本身,但可以定义自身类型的指针变量。例如:
struct node
node n; / /不能定义node型变量
node* next;
};
2.8.2访问结构体内 的元素
访问结构体内的元素有两种方法: .操作和“->”操作。现在把studentInfo 类型定义
成下面这样:
struct studentInfol
int id;
char name [20] ;
studentInfo* next;
}stu, *p;
这样studentInfo中多了一个指针next用来指向下一个学生的地址,且结构体变量中定义
了普通变量stu和指针变量p。
于是访问stu中变量的写法如下:
stu.id
stu. name
stu. next
而访问指针变量p中元素的写法如下:
这样写不够简洁:
(*p) .id
(*p) .name
(*p) .next
一般这样写。
p->id
p-> name
p-> next
2.8.3结构体 的初始化
struct studentInfo{
int id;
char gender ;
studentInfo(int id, char gender) {
id = _id;
gender = _gender;
当然,构造函数也可以简化成1行:
struct studentInfo{
int id;
char gender;
studentInfo(int _id, char _gender): id(_id), gender(_ gender) {}
};
这样就可以在需要时直接对结构体变量进行赋值了:
studentInfostu = studentInfo(10086,'M') ;
#include <stdio.h>
struct Point {
int x,y;
Point(){} / /用以不经初始化地定义pt[10]
Point(int _x, int _y): x(_x),y( _y){}
}pt[10];
int main() {
int num= 0;
for(inti=1;i<=3;i++) {
for(int j = 1;j<= 3;j++) {
pt[num++] = Point(i, j) ;
for(inti=0;i<num;i++) {
printf ("&d, d\n",pt[i].x, pt[i].y) ;
}
return 0;
}