memset () initialized to 1 of those things

Source: Internet
Author: User

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

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.