Sunday, October 13, 2013

memset c++ & c

memset() explanation for both c and c++

courtesy link - 1: http://stackoverflow.com/questions/13327155/memset-definition-and-use

memset() is a very fast version of a relatively simple operation:
void* memset(void* b, int c, size_t len) {
    char* p = (char*)b;
    for (size_t i = 0; i != len; ++i) {
        p[i] = c;
    }
    return b;
}
That is, memset(b, c, l) set the l bytes starting at address b to the value c. It just does it much faster than in the above implementation.

void* memset( void* dest, int ch, std::size_t count );
Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest. If the object is not trivially-copyable (e.g., scalar, array, or a C-compatible struct), the behavior is undefined. Ifcount is greater than the size of the object pointed to by dest, the behavior is undefined.
the code:
#include <iostream>
#include <cstring>
 
int main()
{
    int a[20];
    std::memset(a, 0, sizeof(a));
    for (int ai : a) std::cout << ai;
}



output:
00000000000000000000

No comments:

Post a Comment