What is the advantage of using memset() in C

后端 未结 6 1589
半阙折子戏
半阙折子戏 2020-12-28 09:44

I was curious as to whether or not there was any advantage in regards to efficiency to utilizing memset() in a situation similar to the one below.

Given the followin

6条回答
  •  粉色の甜心
    2020-12-28 10:27

    Your variable p is only required for the initialisation loop. The code for the memset should be simply

    memset( my_buffer, 0, sizeof(my_buffer));
    

    which is simpler and less error prone. The point of a void* parameter is exactly that it will accept any pointer type, the explicit cast is unnecessary, and the assignment to a pointer of an different type is pointless.

    So one benefit of using memset() in this case is to avoid a unnecessary intermediate variable.

    Another benefit is that memset() on any particular platform is likely to be optimised for the target platform, whereas your loop efficiency is dependent on the compiler and compiler settings.

提交回复
热议问题