strncpy()问题

SARA520 2010-08-20 12:14:56

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void)
{
char *src = "hello,worldagain";
char *dest;
int len;

len = strlen(src)+1;

dest = (char *) malloc(sizeof(len));

strncpy(dest, src, len);
//memcpy(dest, src, len);

printf("%s, %d\n", src, strlen(src));
printf("%s, %d\n", dest, strlen(dest));

printf("%d\n", *(src+12));
printf("%d\n", *(dest+12));

return 0;
}


输出结果:
hello,world again,17
hello,world 这个字符我打不出,13
103
11


实在是搞不懂了。。。只要超过12字节就这样
*(dest+12)都是11


用memcpy()也一样
...全文
126 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
SARA520 2010-08-20
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 thefirstz 的回复:]
dest = (char *) malloc(sizeof(len));
这里不需要加sizeof
[/Quote]

恩,这都没看到。。。晕死了!
本来是写sizeof()的,后来改成在外面计算,结果直接把len复制进来了,sizeof没去掉。。。
害我找半天一直找不到。。。

多谢啦
wing_0706 2010-08-20
  • 打赏
  • 举报
回复
看来我 的人品太好了。。。。哎。。
dest = (char *) malloc(sizeof(len));//这一句 居然没看到。。。
dest = (char *) malloc( sizeof(char) * len );
brookmill 2010-08-20
  • 打赏
  • 举报
回复
sizeof(len)结果是4,分配的空间不够,结果就不确定了。
wing_0706 2010-08-20
  • 打赏
  • 举报
回复
我用c-free
结果是
hello,worldagain, 16
hello,worldagain, 16
103
103
请按任意键继续. . .
brookmill 2010-08-20
  • 打赏
  • 举报
回复
dest = (char *) malloc(sizeof(len));
改成 len*sizeof(char)
昵称很不好取 2010-08-20
  • 打赏
  • 举报
回复
dest = (char *) malloc(sizeof(len));
这里不需要加sizeof

69,371

社区成员

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

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