文档详情

c指针及动态内存分配.ppt

发布:2017-04-16约1.44万字共94页下载文档
文本预览下载声明
Lecture 9: Pointers and Dynamic Memory (指针和动态内存分配) ;Chapter Nine: Pointers and Dynamic Memory (指针和动态内存分配) ; Pointers to structures (指向结构体的指针) Pointers to class objects (指向类对象的指针) Pointers as function arguments(指针变量作为函数实参) Dynamic memory allocation(动态内存分配) ;9.1 Variable address(变量地址);Variable address(变量地址); #include iostream #include iomanip using namespace std ; void main() { int var1 = 1 ; float var2 = 2 ; cout var1 has a value of var1 and is stored at var1 endl ; cout var2 has a value of var2 and is stored at var2 endl ; } ;7.1.1 地址与指针;9.2 Pointer variables(指针变量);Pointer variables(指针;说明: ??指针变量定义中,*是一个说明符,它表明其后的变量是指针变量,如在 int * p; 语句中,p是指针变量,而不要认为“*p”是指针变量; 指针变量定义时指定的数据类型不是指针变量本身的数据类型,而是指针变量所指向的对象(或称目标)的数据类型,指针变量只能指向定义时所规定类型的变量; 定义后值不确定,而指针变量一旦被赋值,就有了有效的指向对象; 指针变量并不固定指向一个变量,可指向同类型的不同变量; 指针变量和普通变量的共同点是:它们都能存放数据,而又有自己的地址。不同的是:普通变量中直接存放通常意义下的数据,而指针变量中存放的是地址。;;9.3 the dereference operator * (解引用运算符*);#include iostream using namespace std; main() { int var =1; int* ptr; ptr=var; // ptr contains the address of var cout ptr contains ptr endl ; cout “*ptr contains *ptr endl ; } ;#includeiostream using namespace std; int main() { int *p1,*p2,*p,a,b; cinab; p1=a; p2=b; if(ab) {p=p1;p1=p2;p2=p;} couta=ab=bendl; coutmax=*p1min=*p2endl; return 0; };9.4 Using const with pointers (使用const修饰指针变量); int i=3,j=4; const int* p=i;//*p is a constant but p is not. *p=5; // Illegal: cannot change i using p. i=5; // Legal: i is not a constant. p=j; // Legal: p now point to j. *p=4 int const* p=i; // *p is a constant; p is not. int* const p=i; // p is a constant; *p is not. *p=5; //Legal: *p can be changed. i=5 p=j; //Illegal: p is a constant. (d) const int* const p=i; // both p and *p are constants. *p=5; //Illegal: *p is a constant. p=j; //Illegal: p is a constant. ;指针与常量 —指向常变量的指针;定义指向常变量的指针
显示全部
相似文档