版权声明:欢迎转载请注明转自方辰昱的博客https://blog.csdn.net/viafcccy https://blog.csdn.net/viafcccy/article/details/84886885
一定要注意注释了*的位置 我调试了好久才发现自己没有分配内训
指针定义完一定要记得三选一
1.去null了 2.分配内存 3.指向特定的位置
还有就是宕机基本本质上都跟错误的操作内存有关
还有就是关于字符串的输出问题
首先下面的是正确的但是可以发现这样写编译器会自动输出指针指向的位置之后这个字符数组(字符串)的所有字符
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "Borland International", *str2 = "nation", *ptr;
ptr = strstr(str1, str2);
printf("The substring is: %s\n", ptr);
return 0;
}
下面的写法直接宕机
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "Borland International", *str2 = "nation", *ptr;
ptr = strstr(str1, str2);
printf("The substring is: %s\n", *ptr);
return 0;
}
因为*ptr是指向字符数组的一个字符所以强制字符串输出就会宕机
不封装的程序
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
int find();
find()
{
int num = 0;
int i;
char str[128];
char xCh;
printf("请输入:");
scanf("%s",&str[0]);
printf("请输入需要查找的字符串:");
fflush(stdin);
scanf("%c",&xCh);
for(i = 0;i < 128;i++)
{
if(str[i] == xCh)
{
printf("出现在:%d\n",i+1);
num++;
}
}
printf("共出现%d次",num);
return num;
}
int main()
{
while(1)
{
find();
system("pause");
system("cls");
}
return 0;
}
下面先看封装好的寻找字符的程序
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
int find(char * str , char * xCh , int * count);
int find(char * str , char * xCh , int * count)
{
char * p1 = str;
char * p2 = xCh;
int i = 0 , tmpcount = 0;
if(str == NULL||xCh == NULL)
{
return -1;
}
for(i = 0;i < 128;p1++,i++)
{
if(*p1 == *p2)
{
printf("出现在:%d\n",i+1);
tmpcount++;
}
}
*count = tmpcount;
return 0;
}
int main()
{
while(1)
{
int ret = 0;
char str[128];
char * xCh = (char*)malloc(sizeof(1));//*
int count = 0;
printf("请输入:");
fflush(stdin);
scanf("%s",&str[0]);
printf("请输入需要查找的字符:");
fflush(stdin);
scanf("%c",xCh);
ret = find(str , xCh , &count);
if(ret != 0)
{
printf("erro(%d)",ret);
}
printf("%c共出现%d次",*xCh,count);
system("pause");
system("cls");
}
return 0;
}
下面再看封装好的寻找指定字符串的函数(利用strstrwhile模型)
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
int find(char * str , char * xCh , int * count);
int find(char * str , char * xCh , int * count)
{
char * p1 = str;
char * p2 = xCh;
int i = 0 , tmpcount = 0;
if(str == NULL||xCh == NULL)
{
return -1;
}
do
{
p1 = strstr(p1,p2);
if(p1 != NULL)
{
tmpcount++;
p1++;
}
else
{
break;
}
}while(*p1 != '/0');
*count = tmpcount;
return 0;
}
int main()
{
while(1)
{
int ret = 0;
char str[128];
char xCh[128];
int count = 0;
printf("请输入:");
fflush(stdin);
scanf("%s",str);
printf("请输入需要查找的字符:");
fflush(stdin);
scanf("%s",xCh);
ret = find(str , xCh , &count);
if(ret != 0)
{
printf("erro(%d)",ret);
}
printf("%c共出现%d次",*xCh,count);
system("pause");
system("cls");
}
return 0;
}