指针变量(简称指针)
存放地址的变量。其声明形式与一般变量声明相比只是在变量名前多一个星号*
,接下来看两个例子。
char *p;
*p = 赋值,p += 移动位置
(一)
#include <iostream> using namespace std; int main() { char c[10]="China"; char *p = c; cout<<*p<<endl; cout<<p<<endl; }
/*
输出:C
输出:China
*/
(二)
#include <iostream> using namespace std; int main() { char a[100]; char b[100]; cin.getline(a,100); char* p,* q; p = a; p = p +3; // 指针移动三个位置 q = b; //q 指向b首地址 while(*p != '\0') { * q=* p; q++; p++; } *q='\0'; //末尾赋'\0'结束 cout<<b<<endl; }
/*
输入:asdf qwer
输出:f qwer
*/
指针实战
1.输入的字符串进行处理,去掉首尾的空格
#include <iostream> #include<stdio.h> //#include<string.h> using namespace std; char * trim(char * str); int main() { char s[1024]; cin.getline(s,1024); cout << trim(s) << endl; return 0; } char * trim(char * str) // str 指向s首地址 传入函数相当于s { char *p = str; //p指向str 首地址 while(*p != '\0') //将往后跑到末尾 { p++; } p--; //去掉'\0' while( p>str && *p==' ') //去掉尾空格 { p--; } p++; //取最后一个非空格 移动一位赋'\0' *p='\0'; p = str; //再将p指向str首地址去除首空格 while(*p == ' ') p++; return p; }
/*
输入: asdf df
输出:asdf df
*/
2.本关任务:计算一个字符串(子串)在另一个字符串(长串)中出现的次数。
char * strstr(const char *s1,const char *s2)
扫描字符串 s1,并返回第一次出现 s2 的位置
// 包含字符串函数库 #include <string.h> #include <iostream> using namespace std; int frequency(char * substr, char * str); int main() { char sub[128],str[1024]; cin.getline(sub,128); // 输入子串 cin.getline(str,1024); // 输入长串 int n = frequency(sub,str); // 调用frequency函数,计算子串在长串中出现的次数 cout<<n<<endl; // 输出次数 return 0; } int frequency(char * substr, char * str) { /* substr 小串 str大串*/ char *t=str; int count=0; while (strstr(t,substr)!=NULL) { t=strstr(t,substr); t=t+strlen(substr); count++; } return count; }
/*
输入:ab
aaaabbsafabsdf
输出:2
3.通过函数交换两数
#include <iostream> using namespace std; void x(int *a,int *b) //指针型 { int temp; temp = *a; *a = *b; *b = temp; } void xx(int &a,int &b) //地址型 { int temp; temp = a; a = b; b = temp; } int main() { int a,b; cin>>a>>b; cout<<"指针型"<<endl; //函数实参为地址,虚参为指针 x(&a,&b); cout<<a<<' '<<b<<endl; cout<<"地址型"<<endl; //函数实参为变量本身,虚参为地址型 xx(a,b); cout<<a<<' '<<b; return 0; }