思维导图
在堆区申请两个长度为32的空间,实现两个字符串的比较(非函数实现)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void my_strcmp(char *p,char *q);
int main(int argc, const char *argv[])
{
char *p=(char *)malloc(sizeof(char)*32);
char *q=(char *)malloc(sizeof(char)*32);
printf("please enter first string:");
gets(p);
printf("please enter second string:");
gets(q);
my_strcmp(p,q);
free(p);
free(q);
p=NULL;
q=NULL;
return 0;
}
void my_strcmp(char *p,char *q)
{
int i=0;
while(p[i]==q[i])
{
if(p[i]=='\0')
break;
i++;
}
int sub=p[i]-q[i];
if(sub>0)
printf("%s>%s\n",p,q);
else if(sub<0)
printf("%s<%s\n",p,q);
else
printf("%s=%s\n",p,q);
}
定义函数,在堆区申请空间,两个申请,主函数需要调用2次
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *apply(void);
int main(int argc, const char *argv[])
{
char *q=apply();
printf("%p\n",q);
free(q);
q=NULL;
char *s=apply();
printf("%p\n",s);
free(s);
s=NULL;
return 0;
}
char *apply(void)
{
char *p=(char *)malloc(sizeof(char)*64);
return p;
}
定义函数,实现字符串的输入void input(char *p)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void input(char *p);
int main(int argc, const char *argv[])
{
char *p=(char *)malloc(sizeof(char)*32);
input(p);
return 0;
}
void input(char *p)
{
printf("please enter string:");
gets(p);
puts(p);
}
调用函数实现字符串比较,在主函数中输出大小int my_strcmp(const char *s1,const char *s2)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int my_strcmp(const char *s1,const char *s2);
int main(int argc, const char *argv[])
{
char *s1=(char *)malloc(sizeof(char)*64);
char *s2=(char *)malloc(sizeof(char)*64);
printf("please enter s1:");
gets(s1);
printf("please enter s2:");
gets(s2);
int a=my_strcmp(s1,s2);
if(a>0)
{
printf("s1>s2\n");
}
else if(a<0)
{
printf("s1<s2\n");
}else
{
printf("s1=s2\n");
}
return 0;
}
int my_strcmp(const char *s1,const char *s2)
{
strcmp(s1,s2);
return s1-s2;
}
定义函数,释放空间
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void free_space(int *p);
int main(int argc, const char *argv[])
{
char *p=(char *)malloc(sizeof(char)*64);
strcpy(p,"good study");
printf("%p\n",p);
free_space(p);
printf("%p\n",p);
return 0;
}
void free_space(char *p)
{
free(p);
p=NULL;
}