How to avoid memset pit in C language

Source: Internet
Author: User

Sometimes write code, always feel that the program to write no problem, but always error, looking for a half-day bug, the original is memset () the use of useless to ... In the final analysis is still too slag, in order to prevent later turn this wrong, specifically to check the information and degrees Niang, a kind of sudden feeling ...
void *memset (void *buffer, int ch, size_t count);
The header file for memset () is #include<string.h>
We often use memset () to initialize arrays, which is much more efficient than initializing for loops
, but it must be clear how it is used, otherwise it is easy to initialize errors.
Memset first parameter fills in the first address of the array, the second parameter fills in the initialization, and the third parameter fills in the byte number. This is what everyone knows.

However, look at the following code

#include <stdio.h>
#include <string.h>
int main ()
{
    int a[] = {1,2,3,4,5};
    Memset (A, 1, sizeof (a));
    for (int i = 0; i < 5; i++)
    {
        printf ("%d\n", A[i]);
    return 0;
}

We want to initialize the array of a[5] to 1, but the output turns out to be
16843009
16843009
16843009
16843009
16843009
The reason for this is that the memset initialization is populated by one byte, the int has four bytes, and is populated with 0000 0001 0000 0001 0000 00001 0000 0001, so that the value of each element in the array is 16843009.
The process of memset () can be summed up in one sentence, starting with parameter 1 to fill the parameter 3 bytes with parameter 2. So if the int a[], change to char a[] The result of output is 1. be interested to play.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.