struct Student st=,1000,”zhagnsan”,20-; struct Student*pst=&st;
1)通过结构体变量名来实现 st.sid
2)通过指向结构体变量的指针来实现【重点】 pst->sid
pst所指向的结构体变量中的sid这个成员
CASE 1
#include
int sid;
char name[200]; int age;
}; //分号不能省 Int main(void) { struct Student st=,1000,”zhagnsan”,20-; printf(“%d,%s%d\\n,”,st.sid,st.name,st.age); printf(“%d,%s%d\\n,”,st); //error st.sid=99; //第一种
//st.name=”lisi”; //error strcpy(st.name,”lisi”); st.age=22;
struct Student*pst; pst=&st; //第二种
pst->sid=99; //pst->等价于(*pst).sid,而(*pst).sid等价于st.sid,所以pst->sid等价于st.sid Return 0; }
注意事项:
结构体变量不能加减乘除,但可以相互赋值
普通结构体变量和结构体指针变量作为函数传参的问题 CASE 2
#include
};
void f(struct Student *pst); void g(struct Student st); void g2(struct Student *pst); int main (void) {
struct Student st; //已经为st分配好了内存 f(&st); //g(st); g2(&st);
// printf(“%d %s %d\\n”,st.sid,st.name,st.age); //输出方法一 return 0; }
void g(struct Student st) //整体变量赋值//输出方法二,速度慢,耗空间,耗内存,不推荐 { printf(“%d %s %d\\n”,st.sid,st.name,st.age); }
void g2(struct Student *pst) {
printf(“%d %s %d\\n”,pst->sid,pst->name,pst->age); }
void f(struct Student *pst) {
(*pst).sid=99;
strcpy(pst->name,”zhagnsan”); pst->age=22; }
9_malloc()动态分配内存概述 动态内存的分配和释放 CASE 1
#icclude
可以将pArr当做数组名来操作 //*pArr=4;//类似于a[0]=4; // pArr[1]=10;//类似于a[1]=10; // printf(“%d %d\\n”,*pArr,pArr*1+); //我们可以把pArr当做一个普通数组来使用 for (int i=0;i free(pArr); return 0; //把pArr所代表的的动态分配的20个字节的内存释放 10_跨函数使用内存讲解及其示例 CASE 1 #include int main(void) { int i=10; i=f(); printf(“i=%d\\n”,i); for(i=0;i<2000;++i) f(); return 0; } int f() { int j=20; return j; } CASE 2 main () { int *p; fun(&p); ... } int fun (int **q) { int s; //s为局部变量。调用完毕后s就没有了,最终p没有指向一个合法的整型单 元 *q=&s; } CASE 3 main() { int *p; fun(&p); ... } int fun(int **q) { *q=(int *)malloc(4); //返回4个字节,只取第1个字节地址赋给*q,*q==p。执行完后,因为没有free(),内存没有释放。如果没有free(),整个程序彻底终止时才能释放 } 程序内部类定义方法 A aa=new A(); A *pa=(A*)malloc(sizeof(A)); CASE 4 #include struct Student * CreatStudent(void); void ShowStudent(struct Student *); int main(void) { struct Student *ps; ps=CreatStudent(); ShowStudent(ps); return 0; } struct Student * CreatStudent(void) { struct Student *P=(struct Student *)malloc(sizeof(struct Student)); p->sid=99;
相关推荐: