简体   繁体   中英

Initialize a byte array to a certain value

I want to find an answer for one simple question.

Say we defined a byte array called : x_parms. If I want to make sure that the value in the array is 0, should I do this:

x_parms = new byte[1];

Is this correct?

you need to set the length of the x_params :

x_parms = new byte[21];

or

x_parms = new byte[36];

system will allocate 21 or 36 byte that have 0 as default !

When you write

x_parms = new byte[1];

The 1 means you have an array of length 1.

To set the value to 0, you would use something like

x_params[0] = 0;

Where the first 0 says "set the value in index position 0" and the second 0 means "set the value to be 0".

As others have mentioned in the comment, the default value of byte is 0, so setting it explicitly is not necessary.

For more information, consult https://msdn.microsoft.com/en-us/library/9b9dty7d.aspx . In particular,

The default values of numeric array elements are set to zero

and

Arrays are zero indexed: an array with n elements is indexed from 0 to n-1

In the section titled Array Overview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM