C语言 c语言中的memset函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6816431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
memset function in c language
提问by Jason
I am studying the memset function now, but all the examples are regarding to char array as following:
我现在正在研究 memset 函数,但所有示例都与 char 数组有关,如下所示:
char a[100];
memset(a, 0, 100);
it will set every element in this char array to 0.
它将将此字符数组中的每个元素设置为 0。
I wondered if memset can apply to int array or float array?
我想知道 memset 是否可以应用于 int 数组或 float 数组?
回答by Jason
Yes, it can apply to any memory buffer, but you must input the correct memory buffer size ... memsettreats any memory buffer as a series of bytes, so whether it's char, int, float, double, etc, doesn't really matter. Keep in mind though that it will not set multi-byte types to a specific non-zero value ... for example:
是的,它可以适用于任何内存缓冲区,但你必须输入正确的内存缓冲区大小......memset对待任何内存缓冲区的字节序列,所以无论是char,int,float,double,等,其实并不重要。请记住,它不会将多字节类型设置为特定的非零值......例如:
int a[100];
memset(a, 1, sizeof(a));
will notset each member of ato the value 1 ... rather it will set every bytein the memory buffer taken up by ato 1, which means every four-byte intwill be set to the value 0x01010101, which is not the same as 0x00000001
将未设置各部件的a值1 ...而是将设置的每一个字节中由所占据的存储器缓冲器a到1,这意味着每四个字节int将被设置为的值0x01010101,这是不一样的0x00000001
回答by John Humphreys - w00te
It can be applied to any array. The 100 at the end is the size in bytes, so a integer would be 4 bytes each, so it would be -
它可以应用于任何数组。最后的 100 是以字节为单位的大小,所以一个整数每个是 4 个字节,所以它会是 -
int a[100];
memset(a, 0, sizeof(a)); //sizeof(a) equals 400 bytes in this instance
Get it? :)
得到它?:)
回答by Sebastian Mach
For static-sized and variable-length arrays, you can just
对于静态大小和可变长度的数组,您可以
<arbitrary-type> foo [...];
memset (foo, 0, sizeof (foo)); // sizeof() gives size of entity in bytes
Rule of thumb:Never hardcode [data sizes].
经验法则:永远不要硬编码 [数据大小]。
(This does not work if you pass arrays as function arguments: Behaviour of Sizeof in C)
(如果您将数组作为函数参数传递,则这不起作用:C 中 Sizeof 的行为)

