为什么输出结果不都为0

manrenmanren 2006-11-25 03:42:27
考虑这段代码
long *buf = (long *)malloc(10);
memset(buf,0,1);
int i;
for(i = 0;i < 10;i++)
cout<<buf[i]<<" ";

结果为:0 0 0 135105 0 0 0 0 0 0
为什么不都是0?
在Linux下用gcc编译
...全文
264 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
manrenmanren 2006-12-08
  • 打赏
  • 举报
回复
谢谢。
manrenmanren 2006-12-06
  • 打赏
  • 举报
回复
mark
manrenmanren 2006-11-25
  • 打赏
  • 举报
回复
可以这么用的,错误是在字节的数目上,呵呵。
一分之千 2006-11-25
  • 打赏
  • 举报
回复
long *buf = (long *)malloc(10);
memset(buf,0,1);
这里不对吧?这是一个指针啊!
manrenmanren 2006-11-25
  • 打赏
  • 举报
回复
错了,是一位(^_^)
manrenmanren 2006-11-25
  • 打赏
  • 举报
回复
解决了,谢谢两位朋友的帮助!
谢谢!!
jixingzhong 2006-11-25
  • 打赏
  • 举报
回复
malloc 的单位是字节,
如果malloc(10) 这样是分配10字节,
不是 10 个long 元素 !!

memset 也是一样~~
jixingzhong 2006-11-25
  • 打赏
  • 举报
回复
代码存在很大的问题:

long *buf = (long *)malloc(10*sizeof(long));
memset(buf,0,10*sizeof(long));
int i;
for(i = 0;i < 10;i++)
cout<<buf[i]<<" ";

69,373

社区成员

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

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