Memset()返回值的用途是什么?

声明 memset()以返回与传入函数的地址相同的值 void*

返回值有什么用? 为什么不返回 void

12120 次浏览

It may be used for call chaining like:

char a[200];
strcpy(memset(a, 0, 200), "bla");

The signature is in line with all the other similar functions: memcpy(), strcpy() etc. I always thought this was done to enable one to chain calls to such functions, and to otherwise use such calls in expressions.

That said, I've never come across a real-world situation where I would feel compelled to use the return value in such a manner.

In order to use the function as an argument for another function such as sprintf

I came across this question when Googling to see what memset returned.

I have some code where I test for one value, then if that is true test to see if a value is zeros.

Because there is no completely portable way in C to test for zeros I have to run memset in the middle.

So my code is:

if ( a==true && (memcmp(memset(zeros, 0, sizeof(zeros)), b, sizeof(zeros)) == 0) )

This speaks to the chaining purpose listed in the previous questions, but it is an example of a use for this technique.

I'll leave it to others to judge if this is good coding or not.