- 定义结构体变量及初始化的方法
1)定义类型 用类型定义变量
typedef struct Teacher
{
char name[64];
int age;
int id;
}Teacher;
int main()
{
Teacher t0 = {"Mr Li ziyi",21,01};
strcpy(t0.name,"t1name"); //t1. "."操作符 寻址操作,计算name相对于大变量的偏移量,在cup中计算,没有操作内存
//通过指针的方式 操作 内存空间
Teacher *p = NULL;
p = &t0;
printf("p->age :%d",p->age);// -> 是寻址操作符 算age相对于t0大变量的偏移量
return 0;
}
2)定义类型的同时,定义变量;
struct Teacher
{
char name[64];
int age;
int id;
}t1,t2;
3)直接定义结构体变量;
struct
{
char name[64];
int age;
int id;
}t3,t4;
- 结构体做函数参数:
#include "stdafx.h"
#include<iostream>
#include"string.h"
using namespace std;
typedef struct Teacher
{
char name[10];
int age;
int id;
}Teacher;
void copyTeacher(Teacher *to,Teacher *from)
{
*to = *from;
}
void swapTeacher(Teacher *p1,Teacher *p2)
{
Teacher *tmp = (struct Teacher *)malloc(sizeof(struct Teacher));//必须分配内存空间,否则不能完成赋值操作
copyTeacher(tmp,p1);
*p1 = *p2;
*p2 = *tmp;
if(tmp!=NULL)
{
free(tmp);
}
/*
memcpy(&tmp,p1,sizeof(Teacher));
memcpy(p1,p2,sizeof(Teacher));
memcpy(p2,&tmp,sizeof(Teacher));
*/
}
void printTeacher(Teacher *myarray,int num)
{
int i = 0;
for(i=0;i<num;i++)
{
cout<<"age:"<<myarray[i].age<<endl;
}
}
void sortAge(Teacher *myarray,int num)
{
int i = 0;
bool sorted = false;
while(!sorted)
{
sorted = true;
for(i = 1;i<num;i++)
{
if(myarray[i-1].age<myarray[i].age)
{
swapTeacher(myarray+i-1,myarray+i);
sorted = false;
}
//printTeacher(myarray,3);
//cout<<endl;
}
num--;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Teacher myarray[3];
int i = 0;
int num = 3;
/*
for(i=0;i<num;i++)
{
cout<<"please input the name:";
cin>>myarray[i].name;
}
for(i=0;i<num;i++)
{
cout<<"please input the id:";
cin>>myarray[i].id;
}
*/
for(i=0;i<num;i++)
{
cout<<"please input the age:";
cin>>myarray[i].age;
}
sortAge(myarray, num);
printTeacher(myarray, num);
return 0;
}
问题:
1、给初始化为NULL的结构体指针赋值时,会报错,why?
tmp是NULL的时候,指向安全区域,你解引用就会错误。你申请空间时,因为tmp指向堆空间的申请的区域,是可以解引用的。还有如果你不给申请的指针赋值,然后解引用的话,因为指针指向的是未知区域,也是危险的,回错误。要解引用一个指针,首先指针不能指向安全区域了,然后还不能是指向未知区域。
2、在函数体中(除主函数之外),定义的结构体变量,结构体指针必须初始化,why?