Abstract: when programming C language, you often need to use functions such as memset to initialize arrays or struct. This is a double-edged sword and can easily lead to unexpected bugs. This article mainly analyzes the usage traps of memset functions.
1. a preliminary study of sizeof
The following code is available:
Int a [100], int * B =;
Try to answer these questions: Is sizeof a function? What is the return value of sizeof? Is 100 or 400? What about sizeof B?
Test it by yourself and find the answer.
Conclusion: sizeof is not a function. The returned value is sizef_t, which indicates the size of the byte occupied by the element. Note that it is an unsigned type.
2. Pay attention to function interfaces.
The following code is available:
Int a [100]; memset (a, 0,100 );
Will each element of array a be initialized to 0?
3. Implementation of the memcpy Function
There was a classic problem during the interview: programming and implementing the memcpy function. Its function prototype is as follows:
Void * memcpy (void * dest, const void * src, size_t n );
How to implement it?
Pay attention to the memory overlap and NULL pointer problems, and the negative number of incoming n.
This article does not provide an answer. You can write the answer yourself and compare it with the functions in the standard library.