通过一段程序进一步理解指针的作用。
上代码:
1 #include <stdio.h> 2 3 void find(char array[], char search, char** pa) 4 { 5 int i; 6 for(i=0;*(array+i)!='\0';i++) 7 { 8 if(array[i]==search) 9 { 10 *pa = array+i; 11 **pa = (i+1); 12 break; 13 } 14 15 } 16 } 17 18 int main( void ) 19 { 20 char ch[50]; 21 char c; 22 char* p=NULL; 23 while(1) 24 { 25 int choice; 26 printf("input the string and the key word to be found : \n\n"); 27 scanf("%s %c",ch,&c); 28 find(ch,c,&p); 29 if(p==NULL) 30 { 31 printf("can't find the key word in the string \n\n"); 32 } 33 else 34 { 35 printf("find the first key word in the positon of %d \n\n",*p); 36 } 37 printf("Do you want to exit? input 0 for exit or continue\n"); 38 scanf("%d",&choice); 39 if(choice==0) 40 break; 41 else 42 continue; 43 44 45 } 46 return 0; 47 }
这段程序的功能是匹配字符串中第一个符合给定的字符的字符,并返回其所在字符串的位置。比如字符串abcdeabdc ,给定字符d,则第一个匹配的d位置是4.
解析:首先要理解指针的作用,指针有自己的内存地址,其内存处所对应的是所指向的内存的地址值。举例说明,
char* p ;
char* pi;
char** pa;
pi=p;//pi指向的是p指向的内存地址,即pi与p指向的是同一块内存地址,pi与p的值相同
//*p就是p所指向的内存地址所存储的值
pa=&p;//pa指向的是p的内存地址
//*pa就是pa所指向的内存地址所存储的值,即指针p的值,则**pa等价于*p,就是p所指向的内存地址所存储的值
通过以上的解析,应该比较明了。
转载于:https://www.cnblogs.com/sjlove/archive/2013/04/19/3029808.html