数据结构学习笔记(2)指针和结构体复习

来源:互联网 发布:开源大数据调度系统 编辑:程序博客网 时间:2024/04/30 03:33

一、指针

1、使用指针

#include <stdio.h>#include <stdlib.h>int main(void){double * p;double x=66.6;p=&x;/*x占8个字节,一个字节是8位,一个字节一个地址;但这里并不表示p保存了8个地址,实际上p只保存了一个地址一般p保存的是第一个地址。(虽然这里的x是double类型占8个字节,但是指针变量只占4个字节(它存放的是x变量的地址))*/double arr[3]={1.1,2.2,3.3};double * q;q=&arr[0];printf("%p\n",q);//%p:实际上是以16进制输出,因为地址通常是以16进制输出的q=&arr[1];printf("%p\n",q);system("pause");return 0;/*输出 相差8个字节0018FC6C0018FC74请按任意键继续. . .*/}
2、修改指针变量的值

#include <stdio.h>#include <stdlib.h>void f(int * * p);int main(void){int i;int * p=&i;printf("%p\n",p);f(&p);//修改指针变量的值printf("%p\n",p);system("pause");return 0;/* 输出为:0012FE38FFFFFFFF请按任意键继续. . .*///总结:不管是修改指针变量的值还是其它变量的值,只需要通过其地址进行修改}void f(int * * p){*p=(int *) 0xFFFFFFFF;}

二、结构体

#include <stdio.h>#include <stdlib.h>#include <string.h>//定义一个结构体(struct Student)类型struct Student{int id;char name [200] ;int age;};void inPutStudent(struct Student * pst);void outPutStudent1(struct Student st);void outPutStudent2(struct Student * pst);int main(void){struct Student st;inPutStudent(&st);outPutStudent2(&st);system("pause");return 0;}//为结构体变量的成员赋值void inPutStudent(struct Student * pst){pst->id=0;strcpy(pst->name,"anyliu");/*pst->name="anyliu";Error*/pst->age=24;}/*第一种输出方式需要传208(理论上)个字节(实际上应该比208个字节还大)不推荐这种方式:既耗内存又耗时间*/void outPutStudent1(struct Student st){printf("%d %s %d\n",st.id,st.name,st.age);}//第二种输出方式(只需要传4个字节)void outPutStudent2(struct Student * pst){printf("%d %s %d\n",pst->id,pst->name,pst->age );}