64,682
社区成员
发帖
与我相关
我的任务
分享
//程序功能:编写一个strcpy函数
//程序设计思路:先确定strcpy功能,在写
//程序设计语言:c++
//===========================================
#include <iostream>
using namespace std;
bool Strcpy(const char* str1, char* str2)
{
int i = 0;
int iLen = strlen(str1);
int j = 0;
int jLen = strlen(str2);
if (str1 == NULL || str2 == NULL || iLen > jLen)
{
cout << "array error!" << endl;
return false;
}
while (i < iLen)
{
str2[i] = str1[i];
i++;
}
//str2[i] = '\n';
str2[i] = '\0';
return true;
}
int main(void)
{
int res = 0;
char str1[] = "abcsdsfsfdds";
int iLen = strlen(str1);
cout << "原串的长度:" << iLen << endl;
char* str2 = nullptr;
// str2 = new char [ iLen+1 ] ;
//为什么这里分配的内存空间是iLen的倍数,或者更多啊?????????????
//str2 = (char*)malloc(iLen);
//如果vs下char占用两个字节,那么下面的应该是 2*iLen+2,但是结果不是呀。。。
str2 = (char*)malloc(iLen + 1); //你从哪里知道vs下char占用两个字节?
memset(str2, -1, strlen(str2));
str2[iLen] = 0;
cout << "模式串的长度" << strlen(str2) << endl;
if (str2 == NULL)
{
cout << "new error!" << endl;
return -1;
}
Strcpy(str1, str2);
cout << "源串:" << str1 << "串的长度为:" << strlen(str1) << endl;
cout << "复制后:" << str2 << "串的长度为:" << strlen(str2) << endl;
system("pause");
return res;
}
//原串的长度:12
//模式串的长度12
//源串:abcsdsfsfdds串的长度为:12
//复制后:abcsdsfsfdds串的长度为:12
//请按任意键继续. . .