简体   繁体   English

c语言的memset函数

[英]memset function in c language

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. 它会将此char数组中的每个元素设置为0。

I wondered if memset can apply to int array or float array? 我想知道memset是否可以应用于int数组或float数组?

Yes, it can apply to any memory buffer, but you must input the correct memory buffer size ... memset treats any memory buffer as a series of bytes, so whether it's char , int , float , double , etc, doesn't really matter. 是的,它可以应用于任何内存缓冲区,但是你必须输入正确的内存缓冲区大小... memset将任何内存缓冲区视为一系列字节,因此无论是charintfloatdouble等,都不是真的物。 Keep in mind though that it will not set multi-byte types to a specific non-zero value ... for example: 请记住,它不会将多字节类型设置为特定的非零值...例如:

int a[100];
memset(a, 1, sizeof(a));

will not set each member of a to the value 1 ... rather it will set every byte in the memory buffer taken up by a to 1 , which means every four-byte int will be set to the value 0x01010101 , which is not the same as 0x00000001 不会的每个成员设置a为值1 ...而是将设置在由所占据的存储缓冲器的每一个字节 a1 ,这意味着每四个字节int将被设置为值0x01010101 ,这是不与0x00000001相同

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? 得到它? :) :)

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的行为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM