指针的运算
1.sizeof()
特别的:操作数为数组名时,结果为数组所需存储单元的总字节数
如 sizeof(int)、 sizeof(int *)均为4
声明int myArray[10],*p=myArray;后 sizeof(myArray)为40、 sizeof(p)为4
2.
int v[5], * vPtr = v ; // vPtr 为3000
vPtr += 2; // 赋值后 vPtr 为3008
把 vPtr的值当作整数和 n*sizeof(int)相加,得到vPtr + n的实际值(
指向后续第
n
个数组元
素)
3.同类型指针相减
int v[5], * vPtr , * vPtr2;
vPtr = &v[0];
vPtr2 = &v[2];
// vPtr2 - vPtr 结果为 2.
把 vPtr2和vPtr的值当作整数相减后除以sizeof(int)(
两个指针间的数组元素个数)
4.指针的关系运算
int v[5], * vPtr , * vPtr2;
vPtr = &v[0];
vPtr2 = &v[2];
while( vPtr < vPtr2 )
vPtr++;
5.指针的赋值运算
(1)同类型指针可以赋值
(2)不同类型的指针之间的赋值必须进行强制类型转换
如
int * nPtr;
float f=0.5,* fPtr= &f;
nPtr = (int *) fPtr;
特例:void类型的指针(类型 void *)
- 可以指向任何类型的数据
- void *类型的指针不能被复引用
- 可以和其他类型的指针相互赋值
如:
void * vPtr;
float * fPtr;
vPtr = fPtr;
fPtr = vPtr;
//但下面这种情况不行,必须进行类型的强制转换
void * vPtr;
float * fPtr;
int * iptr;
vPtr = fPtr;
iPtr = vPtr; //错误
iPtr = (int *)vPtr; //正确
常用字符串处理函数
- 求字符串长度: int strlen(const char *s);
- 字符串拷贝: char* strcpy(char* dest, const char* src);
- 字符串连接: char* strcat(char* dest, const char* src);
- 字符串比较: int strcmp(const char* s1, const char* s2);
- 在字符串中查找字符:char* strchr(const char* s, int c);
- 在字符串中反向查找字符:char* strrchr(const char* s, int c);
- 在字符串中查找字符串: char* strstr(const char* s1,const char* s2);
- 打断字符串:char *strtok(char *s, char *delim);
const:
指向常量数据的非常量指针
int i, j, *q;
const int * p;
p = &j; // 允许
p = &i; // 允许
i = 10; // 允许
*P = 5 ; // 不允许
q = P ; // 不允许
指向非常量数据的常量指针
int var1,var2 ;
int * const p = &var1 ;
*P = 5 ; // 允许
P = &var2 ; // 不允许
注:指向非常量数据的常量指针的初值有限制,如
const int var ;
int * const p = &var ; // 错误!
指向常量数据的常量指针
const int val = 10;
const int *const p = &val ;
*P = 5 ; // 不允许
或
int var ;
const int *const p = &var ;
*P = 5 ; // 不允许
var = 5 ; // 允许
用于限定函数形式参数,以保护实参
void output(const double * pd) {
cout << *pd ; // 允许
*pd = 15.5 ; // 不允许!
}
或
void output(const double &d) {
cout << d ; // 允许
d = 15.5 ; // 不允许!
}
动态分配内存
- malloc函数( eg:int *p=(int *)malloc(sizeof(int)); )或运算符new( eg:int *p = new int;int *q = new int[10]; )
- 用malloc函数对应的释放内存函数是free( eg:free(p); )
- 用运算符new对应的释放内存运算符是delete ( eg:delete p; delete [] q; )