69,371
社区成员
发帖
与我相关
我的任务
分享
#include "iostream"
using namespace std;
typedef struct __hstring
{
char *ch;
int length;
__hstring() : ch(0), length(0) // init
{
}
} hstring;//堆分配
extern int strassign(hstring &t,char *chars);
int main()
{
hstring s, t;
if (strassign(s, "sowkdjdls"))
cout<<s.ch<<endl;
if (strassign(t, "skdhfhk"))
cout<<t.ch<<endl;
// release
if (t.ch)
free(t.ch);
if (s.ch)
free(s.ch);
return 0;
}
int strassign(hstring &t, char *chars)
{
if (t.ch)
free(t.ch);
int i = strlen(chars);
if( !i)
{
t.ch = 0;
t.length = 0;
}
else
{
if (!(t.ch = (char*)malloc(i * sizeof(char) + 1))) // size = len + 1
return 0;
for (int j = 0;j <= i-1; ++j)
t.ch[j] = chars[j];
t.ch[i] = '\0'; // '\0' is the end of string
t.length = i;
}
return 1;
}
/*
运行平台:WinXP+Visual C++ 2005 Express
已经改正两个小问题。程序运行正常。
输出为:
sowkdjdls
skdhfhk
请按任意键继续. . .
写的不错,加油哦!
*/
#include <iostream>
using namespace std;
typedef struct
{
char *ch;
int length;
}hstring;//堆分配
int strassign(hstring &t,char *chars);
int main()
{
hstring s,t;
s.ch=0;t.ch=0;//此处加上初始化
if(strassign(s,"sowkdjdls"))
cout <<s.ch <<endl;
if(strassign(t,"skdhfhk"))
cout <<t.ch <<endl;
return 0;
}
int strassign(hstring &t,char *chars)
{
if(t.ch) free(t.ch);
int i=strlen(chars);
if(!i){t.ch=0;t.length=0;}
else
{
if(!(t.ch=(char*)malloc(i*sizeof(char))))
return 0;
for(int j=0;j <=i;++j)//此处把i-1改成i,原因如楼上所述。'\0'
t.ch[j]=chars[j];
t.length=i;
}
return 1;
}