指针定义与应用.pptVIP

  • 0
  • 0
  • 约1.81千字
  • 约 66页
  • 2020-03-09 发布于福建
  • 举报
第15章 指 针;本章主要内容;;;;;什么是指针;什么是指针变量?;指针变量的概念;指针变量的声明;指针变量的初始化;指针变量的初始化;指针与地址运算符;指针与地址运算符;指针变量的赋值运算;指针变量的赋值运算;例1 指针的定义、赋值与使用;;指针变量的算术运算;;;关系运算 两个指针变量指向同一个数组中的元素时,其关系运算的结果表明了这两个指针变量所指向的数组元素的先后关系 指针可以和零之间进行等于或不等于的关系运算。例如:p==0或p!=0;指针的关系运算;;;应用举例2;;应用举例3;;;应用举例4;;;字符指针来存储和处理字符串;用字符数组存储和处理字符串;字符指针的定义、赋值和引用--例5;动态存储分配;动态申请内存操作符 new;动态申请内存操作符 new;动态申请内存操作符 new;释放内存操作符delete;使用动态存储分配时,应注意: 确认分配成功后才能使用。 分配成功后不宜变动指针的值。 用运算符new获取的内存空间,必须用delete进行释放。 对一个指针只能调用一次delete。 在使用delete运算符进行释放时,不用考虑数组的维数。;动态存储分配--例6;cout“please input the length of the array:”endl; cinn; if((p=new int[n])= =0) { cout“can’t allocate memory.”endl; exit(1); } for(i=0;in;i++) p[i]=i*2; cout“now output the array:”endl; for(i=0;in;i++) coutp[i]“ “; coutendl; delete [ ]p; };运行 结果为: please input the length of the array:6 now output the array: 0 2 4 6 8 10 ;引用;按引用调用;按引用调用;按引用调用;用引用参数按引用调用-例7;用引用参数按引用调用-例7;用指针参数按引用调用-例8;用指针参数按引用调用-例8;数组名做函数参数 ;数组名做函数参数;数组名做函数参数;[例9];#includeiostream using namespace std; void invert(int a[ ],int n) { int t=0; for(int i=0;in-1;i++) for(int j=i+1;jn;j++) if(a[i]a[j]) { t=a[i]; a[i]=a[j]; a[j]=t; } };int main( ) { int i; int a[10]; coutInput 10 numbers:endl; for(i=0;i10;i++) cina[i]; invert(a,10); coutThe sorted numbers is:endl; for(i=0;i10;i++) couta[i]endl; return 0; } ;指向数组的指针变量作为函数参数 ;[例10];#include iostream using namespace std; void invert(int *p,int n) { int i,j,temp; for(i=0,j=n-1;ij;i++,j--) { temp=*(p+i); *(p+i)=*(p+j); *(p+j)=temp; } };int main( ) { int a[10],i; //int*q=a; coutInput ten interger:endl; for(i=0;i10;i++) cina[i]; invert(a,10); //invert(q,10); for(i=0;i10;i++) couta[i]endl; return 0; } ;练习---阅读程序写结果;练习---阅读程序写结果;

文档评论(0)

1亿VIP精品文档

相关文档