做了一个函数,把第二个字符串覆盖第一个字符串,但是有问题。
做了一个函数,把第二个字符串覆盖第一个字符串,但是有问题。如果第二个字符串比第一个长,那么输出结果后面有乱码。如果两个字符串一样长,那么只有第一个字符被覆盖。
程序代码:#include <stdio.h>
#include <string.h>
#define SIZE 81
char *cpy (char *psx, char *psy);
int main (void)
{
char str1[SIZE];
char str2[SIZE];
char* ps1;
char* ps2;
printf ("Enter firse string:\n");
ps1 = gets (str1);
printf ("Enter second string:\n");
ps2 = gets (str2);
cpy (ps1, ps2);
puts (ps1);
system ("pause");
return 0;
}
char *cpy (char *psx, char *psy)
{
int i = 0;
if (strlen (psx) > strlen (psy))
{
while (psx[i] != '\0')
{
psx[i] = psy[i];
i++;
}
}else if (strlen (psx) < strlen (psy))
{
while (psy[i] != '\0')
{
psx[i] = psy[i];
i++;
}
}else
{
while (psx[i] != '\0')
{
psx[i] = psy[i];
i++;
}
}
return psx;
}[此贴子已经被作者于2015-11-12 10:31编辑过]



