请教memset函数的用法及例子

szsailing 2003-09-22 04:05:52
哪位大侠能给一个在linux下编译通过的说明memset函数用法的例子?
...全文
180 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
grail0922 2003-09-23
  • 打赏
  • 举报
回复
#include <string.h>
void *memset( void *dst, int c, size_t length );

Description:

The memset function fills the first length characters of the object pointed to by dst with the value c.

Returns:


但是对含有虚函数的类对象不能使用memset,因为会破坏虚拟表指针vtrl.
The memset function returns the pointer dst.

See Also:

memchr, memcmp, memcpy, memicmp, memmove

Example:

#include <string.h>

void main()
{
char buffer[80];

memset( buffer, '=', 80 );
}

Classification:

memset is ANSI

Systems:
wgzh 2003-09-23
  • 打赏
  • 举报
回复
这是因为char *s="Golden Global View";定义使字符串指针s指向常量字符串"Golden Global View",而接下来的语句memset(s,'G',6)试图改变指针s指向的值(常量字符串),常量不能改变的,所以出错。
你改成这样:
#include <string.h>
int main()
{
char s[]="Golden Global View";
memset(s,'G',6);
printf("%s",s);

return 0;
}
或者下面这样都可以的:
#include <string.h>
#include <stdlib.h>
int main()
{
char *s;
s = (char *)malloc(sizeof("Golden Global View")+1);
strcpy( s,"Golden Global View" );
memset(s,'G',6);
printf("%s\n",s);

return 0;
}
szsailing 2003-09-23
  • 打赏
  • 举报
回复
哪位大侠帮我看看如下代码为何在linux下编译通过,但是运行的时候
出现Segmentation fault

#include <string.h>

main()
{
char *s="Golden Global View";
memset(s,'G',6);
printf("%s",s);

return 0;
}
wgzh 2003-09-22
  • 打赏
  • 举报
回复
#include<string.h>
函数原型:void *memset(void * buf,char ch,size_t count);
作用:把ch中的值复制到buf指向的内存空间的前count字节处,并返回buf指针.
也就是把一段分配的内存初始化为确定的值~

例如:
char a[20];
memset( a,0,10 ); //将数组a前10个元素用零初始化(赋值为0)
memset( &a[10],1,10 ); //将数组a后10个元素用1初始化(赋值为1)
szsailing 2003-09-22
  • 打赏
  • 举报
回复
要include 什么库?
xfxfxf 2003-09-22
  • 打赏
  • 举报
回复
char m[128];
memset(m,0,128);

24,855

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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