vs下内char存分配问题

C++语言 码拜 9年前 (2015-05-11) 1002次浏览 0个评论
 

//===================================================================
//程序功能:编写一个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”” ;
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);
memset(str2,-1,strlen(str2) );
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 ;

}
这里有问题vs下内char存分配问题

20分
修改如下:

//程序功能:编写一个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
//请按任意键继续. . .
引用 1 楼 zhangxiangDavaid 的回复:

[/code]

谢谢,没注意到这个问题


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明vs下内char存分配问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!