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 == '')
{
if(count>2) word++;
break;
}
else {
do{
str++;

}while(*str != ' ' && *str!= '');
}
}
return word;

}
int main(int argc, const char *argv[])
{
char str[100];
printf("please input a str:");
scanf("%[^ ]",str);

int ret = -1;

ret = wordcount(str);

printf("word in str:%d ",ret);
return 0;
}

使用二级指针:

#include <stdio.h>

int count(char **p){

(*p)++;
if(**p == ' ' || **p == '')return 0;
while(**p !=' ' && **p != ''){
if(**p < 'A' || (**p > 'Z' && **p < 'a') || **p > 'z'){
do{
(*p)++;
}while(**p != ' ' && **p != '');
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!= '');
}
}
return word;

}
int main(int argc, const char *argv[])
{
char str[100];
printf("please input a str:");
scanf("%[^ ]",str);

int ret = -1;

ret = wordcount(str);

printf("word in str:%d ",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; //数组尾指针指向
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("%[^ ]",str);

printf("str before:%s ",str);

spacetohello(str);

printf("str after:%s ",str);
return 0;
}

不适用二级指针代码

#include <stdio.h>

void spacetohello(char *str){
char *t; //移动寻找space指针
char *tail; //数组尾指针指向
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("%[^ ]",str);

printf("str before:%s ",str);

spacetohello(str);

printf("str after:%s ",str);
return 0;
}

原文地址:https://www.cnblogs.com/huiji12321/p/11151667.html