大运河购物中心品牌图:求VC++两个语句的解释?

来源:百度文库 编辑:中科新闻网 时间:2024/04/29 14:15:49
char buf[4080];//缓冲区
memset(buf,0,4080);
这个是有关缓冲去的,请详细解释一下,谢谢!
谢谢一楼的,那个好像是MSDN里的。按它说的第二个语句是把缓冲区里都写“0”吗?为什么要这样?

在有些情况下申请了缓冲区, 但你不能保证缓冲区里面的数据都是初始为0的, 可能是些乱字符,这样, 就要用到memset来初始缓冲区内容 , 一般就是初始其为0.

缓冲区--实际就是一段内存区域
就象你的例子里面定义的buf,
它是char型的类型有4086个字节大小.
如果你定义的是int buf[4086]的缓冲区
的话就有4086*4个字节大小.
特别注意的就是,当缓冲区的类型为char型时
用memset(buf,0,sizeof(buf))是为了在使用
的时候防止读取缓冲区出错或者读取越界
因为,C语言中定义的变量没有初始化的话就是随机值
可能造成字符串数组中没有'\0'结束标志,调用
memset()函数就是将缓冲区里的每个元素都置为'\0'
这样在后面使用的过程中就不用手动地在缓冲区
赋值后在加'\0'了,也能防止因疏忽大意而少加结束标志
造成的读取错误或越界.

Sets buffers to a specified character.

void *memset(
void *dest,
int c,
size_t count
);
wchar_t *wmemset(
wchar_t *dest,
wchar_t c,
size_t count
);
Parameters
dest
Pointer to destination.
c
Character to set.
count
Number of characters.
Return Value
The value of dest.

Remarks
Sets the first count chars of dest to the character c.

Example
// crt_memset.c
/* This program uses memset to
* set the first four chars of buffer to "*".
*/

#include <memory.h>
#include <stdio.h>

int main( void )
{
char buffer[] = "This is a test of the memset function";

printf( "Before: %s\n", buffer );
memset( buffer, '*', 4 );
printf( "After: %s\n", buffer );
}
Output
Before: This is a test of the memset function
After: **** is a test of the memset function

第一句是创建一个长度为4080字节的缓冲区
第二句是把buf指针内4080字节的数据全部置为0

moxsone 说的详细明确,好

创建缓冲区并将字节全部设置为0