结构体的认识

  • 结构体的定义
    将不同数据类型的数据对象组织在一起。
  • 结构体在c中和C++不同
    在C中的结构体只能自定义数据类型,结构体中不允许有函数,而C++中的结构体可以加入成员函数。C中的结构体只涉及到数据结构,而不涉及到算法,也就是说在C中数据结构和算法是分离的,而到C++中一类或者一个结构体可以包含函数(这个函数在C++我们通常中称为成员函数),C++中的结构体和类体现了数据结构和算法的结合。

结构体的定义、初始化

  • 一般结构体
struct test//定义一个名为test的结构体 
{ 
 int a;//定义结构体成员a 
 int b;//定义结构体成员b 
}; 
test pn1;//定义结构体变量pn1 
test pn2;//定义结构体变量pn2 

pn2.a=10;//通过成员操作符.给结构体变量pn2中的成员a赋值 
pn2.b=3;//通过成员操作符.给结构体变量pn2中的成员b赋值 
test* point;//定义结构指针 
point=&pn2;//指针指向结构体变量pn2的内存地址

point->a=99;//通过结构指针修改结构体变量pn2成员a的值 

 

  • 含有指针
struct Student{   
        char *name;   
        int score;   
        struct Student* next;   
    };  
//重点记住,在结构体中含有指针需要为指针指定指向的内存地址
Student stu,*pStu;
//结构体成员需要初始化
stu.name = new char;//stu.name = (char*)malloc(sizeof(char));
strcpy(stu.name,"ddd");
stu.score = 99;
//结构体成员需要初始化
Pstu = new Student;//Pstu = malloc(sizeof(Student));
Pstu->name = new char//在用结构体指针的=时候先为整个结构体分配内存,然后再为结构体内部的指针申请内存。

//最后在根据那个地方new,然后进行delete
delete stu.name;
stu.name = null;
delete Pstu.name;
Pstu->name = null;
delete Pstu;
Pstu = null;
//记住最后一定将指针赋值为null,防止指针乱指,成为野指针。
View Code

 

  • 结构体嵌套
struct Data
{ 
int year;
int month;
int day;
}
struct stu /*定义结构体* / 
{ 
    char name[20]; 
    long num; 
    struct data birthday; /嵌*套的结构体类型成员*/ 
} ;

//结构体初始化
struct stu a;
a.name = "gaoqinag";//在声明的时候自动在栈为数组进行内存分配
a.birthday.year = 2013;//对于嵌套的结构体同样适用,自动 申请内存。
a.birthday.month = 12;
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案