Memset Definition and use

后端 未结 6 681
失恋的感觉
失恋的感觉 2020-12-12 16:24

What\'s the usefulness of the function memset()?.

Definition: Sets the first num bytes of the block of memory pointed by

6条回答
  •  萌比男神i
    2020-12-12 16:52

    memset() is usually used to initialise values. For example consider the following struct:

    struct Size {
        int width;
        int height;
    }
    

    If you create one of these on the stack like so:

    struct Size someSize;
    

    Then the values in that struct are going to be undefined. They might be zero, they might be whatever values happened to be there from when that portion of the stack was last used. So usually you would follow that line with:

    memset(&someSize, 0, sizeof(someSize));
    

    Of course it can be used for other scenarios, this is just one of them. Just think of it as a way to simply set a portion of memory to a certain value.

提交回复
热议问题