char*strcpy(char *s1, char *s2)
{
char*temp = s1;
while (*s2 != '\0')
{
*s1++ = *s2++;
}
s1 = '\0';
return temp;
}
为什么一运行到*s1++=*s2++就出错。新人求教
main函数中修改:
char *s1="abc"; s1指向静态常量存储区域,一般不允许通过指针修改
char s1[]="abc", s2[]="def";
#include<stdio.h>
//strcpy 的实现
char* strcpy1(char *s,char *t)
{
char *temp = s ;
while((*s++ = *t++))
;
return temp;......
答案就在这里:strcpy实现 空指针的问题。
----------------------Hi,地球人,我是问答机器人小S,上面的内容就是我狂拽酷炫叼炸天的答案,除了赞同,你还有别的选择吗?
#include"stdio.h"
char*strcpy(char *s1, char *s2)
{
char*temp = s1;
while (*s2 != '\0')
{
*s1++ = *s2++;
}
*s1 = '\0';//修改
return temp;
}
int main()
{
char str1[20],str2[20]="i love vc";
strcpy(str1,str2);
printf("%s\n",str1);
}
#include<iostream>
using namespace std;
int strcmp(char *s1, char *s2)
{
while (*s1 != '\0'&&*s2 != '\0'&&*s1 == *s2)
{
s1++;
s2++;
}
return *s1 - *s2;
}
char*strcpy(char *s1, char *s2)
{
char*temp = s1;
while (*s2 != '\0')
{
cout << *s1 << endl;
*s1++ = *s2++;
}
*s1 = '\0';
return temp;
}
char*strcat(char *s1, char *s2)
{
char*temp = s1;
while (*s1 != '\0') s1++;
while (*s2 != '\0')
{
*s1++ = *s2++;
}
*s1 = '\0';
return temp;
}
int strlen(char *s1)
{
int i = 0;
for (i = 0; s1[i] != '\0'; i++);
return i;
}
void main()
{
char*s1="abc", *s2="def";
cout << "strlen(s1)=" << strlen(s1) << endl;
cout << "strlen(s2)=" << strlen(s2) << endl;
cout << "strcmp(s1,s2)=" << strcmp(s1, s2) << endl;
cout << "strcpy(s1,s2)=" << strcpy(s1, s2) << endl;
cout << "strcat(s1,s2)=" << strcpy(s1, s2) << endl;
}