1.多文件定义函数字符串连接拷贝比较
头文件
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *create();
int my_strcmp(char *p1,char *p2);
char *my_strcpy(char *p1,char *p2);
char *my_strcat(char *p1,char *p2);
char *free_space(char *p);
定义函数
#include "head.h"
char *create()
{
char *p = (char *)malloc(sizeof(char)*100);
if(p == NULL)
return NULL;
return p;
}
int my_strcmp(char *p1,char *p2)
{
int i = 0;
while(*(p1+i) == *(p2+i))
{ if(*(p1+i) == '\0')
break;
i++;
}
int dev = *(p1+i) - *(p2+i);
return dev;
}
char *my_strcpy(char *p1,char *p2)
{
char *p3 = p1;
while(*p2!='\0')
{
*p3++ = *p2++;
}
*p3 = *p2;
return p1;
}
char *my_strcat(char *p1,char *p2)
{
char *p3 = p1;
char *p4 = p2;
int i,j;
for ( i = 0;*(p3+i)!='\0';i++);
for ( j = 0;*(p4+j)!='\0';i++,j++)
*(p3+i) = *(p4+j);
*(p3+i)='\0';
return p1;
}
char *free_space(char *p)
{
if(p == NULL)
return NULL;
free(p);
p = NULL;
return p;
}
主函数
#include "head.h"
int main(int argc, const char *argv[])
{
char *p1 = create();
char *p2 = create();
printf("请输入p1:");
scanf("%s",p1);
printf("请输入p2:");
scanf("%s",p2);
int dev = my_strcmp(p1,p2);
if (dev > 0)
printf("p1 > p2\n");
else if(dev < 0)
printf("p1 < p2\n");
else if (dev = 0)
printf("p1 = p2\n");
printf("拷贝后p1 = %s\n",my_strcpy(p1,p2));
printf("连接后p1 = %s\n",my_strcat(p1,p2));
p1 = free_space(p1);
p2 = free_space(p2);
return 0;
}
2.定义学生结构体(姓名,性别,分数)定义两个学生变量实现两个学生信息交换
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Student
{
char name[10];
char sex[10];
float score;
};
void output(struct Student a)
{
printf("姓名\t性别\t成绩\n");
printf("%s\t%s\t%.1f\n",a.name,a.sex,a.score);
puts("");
}
int main(int argc, const char *argv[])
{
struct Student a = {"张三","男",89.5};
printf("学生a信息为:\n");
output(a);
struct Student b = {"李四","女",99.5};
printf("学生b信息为:\n");
output(b);
char s[10] = {0};
strcpy(s,b.name);
strcpy(b.name,a.name);
strcpy(a.name,s);
strcpy(s,b.sex);
strcpy(b.sex,a.sex);
strcpy(a.sex,s);
float t = 0;
t = b.score;
b.score = a.score;
a.score = t;
printf("交换后学生a信息为:\n");
output(a);
printf("交换后学生b信息为:\n");
output(b);
return 0;
}