看看哪里错了????实在找不出错误了

nandizhu 2008-02-25 11:00:26
实现一个串的赋值问题的

#include <iostream>
#include"struct.h"
using namespace std;
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;
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-1;++j)
t.ch[j]=chars[j];
t.length=i;
}
return 1;
}

typedef struct
{
char *ch;
int length;
}hstring;//堆分配
...全文
81 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
星羽 2008-02-26
  • 打赏
  • 举报
回复

#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;
}


visame 2008-02-26
  • 打赏
  • 举报
回复
arong1234是对的,我大意了。。。羞愧阿。。。
arong1234 2008-02-26
  • 打赏
  • 举报
回复
除了你说的修改,还要改这个

if(!(t.ch=(char*)malloc((i+1)*sizeof(char))))
另外:别用i这样的变量名,名字得体现含义
visame 2008-02-26
  • 打赏
  • 举报
回复

/*
运行平台: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;
}
arong1234 2008-02-25
  • 打赏
  • 举报
回复
字符串需要的空间比strlen要多一个字节来保存'\0'

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧