memset function in c language

孤人 提交于 2019-12-03 03:54:57

问题


I am studying the memset function now, but all the examples are regarding to char array as following:

char a[100];
memset(a, 0, 100);

it will set every element in this char array to 0.

I wondered if memset can apply to int array or float array?


回答1:


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. 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




回答2:


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 )




回答3:


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 -

int a[100];
memset(a, 0, sizeof(a)); //sizeof(a) equals 400 bytes in this instance

Get it? :)



来源:https://stackoverflow.com/questions/6816431/memset-function-in-c-language

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!