Problem code:
1#include <stdio.h>2#include <string.h>3 intMain () {4 intarray[5];5 intA;6 while(~SCANF ("%d",&a)) {7memset (Array,a,sizeof(array));8printf"%d%d\n", array[0],array[1]);9 }Ten return 0; One}
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:
Very simply, the memset is a byte-by-byte set, which is assigned the last 8 bits of the value to be assigned.
The binary of 1 is (00000000 00000000 00000000 00000001), takes 8 bits (00000001), int is 4 bytes, and when initialized to 1 o'clock, it sets each byte of an int to 1, which is 0x01010101, Binary is 00000001 00000001 00000001 00000001, and decimal is 16843009.
It is purely coincidental that the reason for entering 0,-1 is correct.
0, Binary is (00000000 00000000 00000000 00000000), after taking 8 bits (00000000), after initialization 00000000 00000000 00000000 00000000 The result is 0
-1, negative numbers in the computer in the complement of storage, binary is (11111111 11111111 11111111 11111111), after the 8 bit (11111111), then 11111111 11111111 11111111 11111111 Results also-1
Summary: memset () is correct only when initializing -1,0. If you want to initialize to another value, just be a DIY!
Like what:
1 int a[]; 2 for (int i=0;i<sizeof(a)/sizeof(int); i++) {3 a[i]=1; 4 }
memset () initialized to 1 of those things