一、指针的识别
C/C++语言中的指针变量可以指向任何类型的对象,包括数组、类对象、结构和函数,另外,数组的数组元素、结构的成员和函数的参数也都可以是指针类型。
一种理解和构造对象说明的方法是:先不看标识符,按从右到左的顺序逐个解释每个说明符,如果有括号,则改变解释的先后顺序,先解释括号内再解释括号外。
char *ptr[4] = {"bbbb", "aefa", "ahia"};
4个元素的数组、每个元素是一个指针、指针指向char型,所以ptr是一个有4个char型指针作为数组元素的数组。
char(*ptrr)[4]
这是一个指针,指针指向一个包含4个元素的数组,每个元素是一个char型,所以ptrr是一个指向4个char型数的数组的指针。
二、二级指针与二维数组
指向一维数组的指针与数组名是等效的。
例如,int a[10],*pa =a;
其中pa[0]实际上就是a[0],*pa也就是a[0],*(pa+1)和pa[1]都代表a[1]。
二维数组是数组元素为一维数组的数组,所以指针类型应该是指向一维数组整体的指针类型。例如
int x2d[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
指向一维数组整体的指针定义如下:数据类型 (*指针变量名)[n]
int (*pt)[4]=x2d; //指针pt和x2d是等效的,它们表示的首地址一样,所指目标类型也一样。
数组元素的n不可以省略。省略后就无法确定指针目标占有多少个字节了。这样的指针指向的目标是一维数组整体,所以指向的目标是一维数组的首地址,所以它可以看作是指向指针的指针,称为二级指针。
x2d指向的是一个由指针组成的数组,包括x2d[0]、x2d[1]、x2d[2]。
三、指针数组用于表示字符串
在一些字符串中搜索某个特定的字符值,使用指针数组表示字符串。strings是一个指向指针数组的指针,value是我们查找的字符串,注意指针数组以一个null指针结束。
/* Given a pointer to a NULL-terminated list of pointers, search
the strings in the list for a particular character.*/
#include "stdafx.h"
#include <stdio.h>
#include "iostream"
using namespace std;
#define TRUE 1
#define FALSE 0
int find_char( char **strings, char value )
{
char *string; /* the string we're looking at */
int count=0;
/*
** For each string in the list ...
*/
while( ( string = *strings++ ) != NULL ){ //string指向*strings的字符串
/*
** Look at each character in the string to see if
** it is the one we want.
*/
while( *string != '\0' ){
if( *string++ == value )
count=count+1;
}
return count;
}
return FALSE;
}
int _tmain(int argc, _TCHAR* argv[])
{
char *ptr[4] = {"bbbb", "aefa", "ahia",NULL}; //一个有4个char型指针作为数组元素的数组
int temp=0;
for(int j=0;j<=2;j++)
{
int i=find_char(ptr+j , 'a' ); //指向指针数组的指针
temp=temp+i;
cout<<"第"<<j<<"个字符串中a的个数: "<<i<<endl;
}
cout<<"a的个数: "<<temp<<endl;
system("pause");
return 0;
}
分析while( ( string = *strings++ ) != NULL )语句,(1)它将strings当前所指向的指针复制到变量string中,(2)它增加strings的值,使它指向下一个值 (3)它测试string是否为NuLL。当string指向当前字符串中作为终止标志的NUL字节时 ,内层的while循环就终止。 *strings分别为"bbbb", "aefa", "ahia",NULL。
四、数组指针
用指向二维数组基本元素的指针变量,再用指向组成二维数组的一维数组的指针变量输出二维数组的全部基本元素。
// arraypointer.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int a[3][6]={{1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18}};
int *ptr,i,j;
ptr=&a[0][0];
for(i=0;i<18;i++){
cout<<*(ptr+i)<<'\t';
if(i%6==5)cout<<endl;
}
cout<<endl;
int (*ptr1)[6];//指向包含6个整型元素的一维数组的指针
ptr1=a;
for(i=0;i<3;i++){
for (j=0;j<6;j++)
cout<<*(*(ptr1+i)+j)<<'\t';
cout<<endl;
}
system("pause");
return 0;
}