Correct use of memset

Today, I did a question on the list of prime numbers. I used memset when using an array to record whether it is a prime number. I cleared all the numbers in the array to 1, which means it is a prime number, not a prime number, so I changed it to 0. I am judging this Whether a number is prime depends on whether it is 0 or 1. The result has always been a problem. After my step-by-step debugging, I found a bug that I never cared about before. memset can only clean up int arrays to 0 or -1! ! !

Let's verify:

#include <stdio.h>
#include <string.h>
int main() {
    int array[5];
    int a;
    while(~scanf("%d",&a)){
        memset(array,a,sizeof(array));
        printf("%d  %d\n",array[0],array[1]);
    }
    return 0;
}

Program function: Initialize array elements as input values.

Input:
-1

0

1

Expected output:
-1 -1
0 0
1 1

Actual output:
-1 -1
0 0
16843009 16843009

reason:

memset is assigned by bytes, and the last 8 binary bits of variable a are assigned.

The binary of 1 is (00000000 00000000 00000000 00000001), take the last 8 bits (00000001), and the int type occupies 4 bytes. When initialized to 1, it sets each byte of an int to 1, which is 0x01010101 , binary is 00000001 00000001 00000001 00000001, decimal is 16843009.

The reason why it is correct to enter 0,-1 is the principle.

0, binary is (00000000 million), after the post-8 bits (00000000
) The last 8 digits (11111111) are 11111111 11111111 11111111 11111111 and the result is also -1

 

This is the original code of memset in the c standard library:

 

1 void *(memset)(void *s, int c, size_t n)
2 {
3     const unsigned char uc = c;
4     unsigned char *su;
5     for (su = s; 0 < n; ++su, --n)
6         *su = uc;
7     return (s);
8 }

 

The source code shows that the array parameters are assigned in the form of character arrays.

When initializing an array of byte units, you can use memset to initialize each array element to any value you want, for example,

1 char data[10];
2 memset(data, 1, sizeof(data));    // right
3 memset(data, 0, sizeof(data));    // right

 

And if I want to assign the int array to the value I want, I will only DIY it myself

1 int a[11];
2 for(int i=0; i<sizeof(a)/sizeof(int); i++)
3 {
4     a[i]=1;
5 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325376865&siteId=291194637