step1.day11 C语言基础练习之指针和二级指针
梳理了好長時間,總是分不清為什么一級指針能干的事兒為啥引入二級指針,據一個驅動工程師說還是挺常用的,忍者難受嘗試使用了一下二級指針。
遇到一個問題是,如果想讓一級指針指向移動,二級指針需要的格式是(*p)++,而不是*p++,這是和一級指針不同的地方,寫了兩個對比的小例子,如下:
1.數輸入的單詞個數,不使用二級指針
#include <stdio.h>
int wordcount(char *str){
int count;
int word = 0;
while(*str){
count = 0;
while((*str>='a' && *str<='z') || (*str>='A' && *str<='Z')){
count++;
str++;
}
if(*str == ' '){
if(count>2) word++;
str++;
continue;
}
else if(*str == '\0')
{
if(count>2) word++;
break;
}
else {
do{
str++;
}while(*str != ' ' && *str!= '\0');
}
}
return word;
}
int main(int argc, const char *argv[])
{
char str[100];
printf("please input a str:");
scanf("%[^\n]",str);
int ret = -1;
ret = wordcount(str);
printf("word in str:%d\n",ret);
return 0;
}
使用二級指針:
#include <stdio.h>
int count(char **p){
(*p)++;
if(**p == ' ' || **p == '\0')return 0;
while(**p !=' ' && **p != '\0'){
if(**p < 'A' || (**p > 'Z' && **p < 'a') || **p > 'z'){
do{
(*p)++;
}while(**p != ' ' && **p != '\0');
return 0;
}
else (*p)++;
}
return 1;
}
int wordcount(char *str){
int word = 0;
while(*str){
if(*str == ' '){
str++;
continue;
}
else if((*str>='a' && *str<='z') || (*str>='A' && *str<='Z'))
{
word += count(&str);
}
else {
do{
str++;
}while(*str != ' ' && *str!= '\0');
}
}
return word;
}
int main(int argc, const char *argv[])
{
char str[100];
printf("please input a str:");
scanf("%[^\n]",str);
int ret = -1;
ret = wordcount(str);
printf("word in str:%d\n",ret);
return 0;
}
2.輸入字符串,在字符串處插入hello,使用二級指針代碼
#include <stdio.h>
void insert(char **p,char **q)
{
while(*p < *q){
*(*q+4) = **q;
(*q)--;
}
while(**q) (*q)++;
**p = 'h';
*(*p+1) = 'e';
*(*p+2) = 'l';
*(*p+3) = 'l';
*(*p+4) = 'o';
*p = *p+5;
}
void spacetohello(char *str){
char *t; //移動尋找space指針
char *tail; //數組尾指針指向\0
tail = str;
t = str;
while(*tail) tail++;
while(*t){
if(*t == ' ')
insert(&t,&tail);
else t++;
}
}
int main(int argc, const char *argv[])
{
char str[100];
printf("please input a str:");
scanf("%[^\n]",str);
printf("str before:%s\n",str);
spacetohello(str);
printf("str after:%s\n",str);
return 0;
}
不適用二級指針代碼
#include <stdio.h>
void spacetohello(char *str){
char *t; //移動尋找space指針
char *tail; //數組尾指針指向\0
tail = str;
t = str;
while(*tail) tail++;
while(*t){
if(*t == ' '){
while(t < tail){
*(tail+4) = *tail;
tail--;
}
while(*tail) tail++;
*t = 'h';
*(t+1) = 'e';
*(t+2) = 'l';
*(t+3) = 'l';
*(t+4) = 'o';
t = t+5;
}
else t++;
}
}
int main(int argc, const char *argv[])
{
char str[100];
printf("please input a str:");
scanf("%[^\n]",str);
printf("str before:%s\n",str);
spacetohello(str);
printf("str after:%s\n",str);
return 0;
}
轉載于:https://www.cnblogs.com/huiji12321/p/11151667.html
總結
以上是生活随笔為你收集整理的step1.day11 C语言基础练习之指针和二级指针的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: step1 . day10 C语言基础练
- 下一篇: LeetCode 1004.最长连续1的