问题描述
- strcpy的实现问题。。。。
-
char*strcpy(char *s1, char *s2)
{
char*temp = s1;
while (*s2 != '')
{
*s1++ = *s2++;
}
s1 = '';
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实现 空指针的问题。
解决方案三:
#include"stdio.h"
char*strcpy(char *s1, char *s2)
{
char*temp = s1;
while (*s2 != '')
{
*s1++ = *s2++;
}
*s1 = '';//修改
return temp;
}
int main()
{
char str1[20],str2[20]="i love vc";
strcpy(str1,str2);
printf("%s
",str1);
}
解决方案四:
#include<iostream>
using namespace std;
int strcmp(char *s1, char *s2)
{
while (*s1 != ''&&*s2 != ''&&*s1 == *s2)
{
s1++;
s2++;
}
return *s1 - *s2;
}
char*strcpy(char *s1, char *s2)
{
char*temp = s1;
while (*s2 != '')
{
cout << *s1 << endl;
*s1++ = *s2++;
}
*s1 = '';
return temp;
}
char*strcat(char *s1, char *s2)
{
char*temp = s1;
while (*s1 != '') s1++;
while (*s2 != '')
{
*s1++ = *s2++;
}
*s1 = '';
return temp;
}
int strlen(char *s1)
{
int i = 0;
for (i = 0; s1[i] != ''; 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;
}
时间: 2024-10-28 11:17:09