Home > database >  Error during subtraction of a variable in bytes in C#
Error during subtraction of a variable in bytes in C#

Time:08-25

Subtraction of a variable in bytes in C# is pretty simple, but not worked for me in the loop. My code:

public static byte[] GetRandomArray(int size)
  {
     Random rnd = new Random();
     byte[] b = new byte[size];
     rnd.NextBytes(b);
     return b;
  }

private void button1_Click(object sender, EventArgs e)
{
byte[] a2 = GetRandomArray(8);
byte[] b2 = a2;
for (int x = 0; x < 8; x  )
    {
      a2[x]=(byte)(a2[x] - 1);
      MessageBox.Show(a2[x].ToString()   "  |  "   b2[x].ToString());
    }
}

Finally a2[x] is equal to b2[x]. No anything changes. What's the problem?

CodePudding user response:

The subtraction is working, but is is changing b2[x] as wel.

I have used this code

using System;                   
public class Program
{
    public static void Main()
    {
        byte[] a2 = GetRandomArray(8);
        byte[] b2 = a2;
        Console.WriteLine(string.Join(",",a2));     
        Console.WriteLine(string.Join(",",b2));
        for (int x = 0; x < 8; x  )
        {
            a2[x]=(byte)(a2[x] - 1);            
        }
        Console.WriteLine(string.Join(",",a2));
        Console.WriteLine(string.Join(",",b2));
    }
    public static byte[] GetRandomArray(int size)
    {
        Random rnd = new Random();
        byte[] b = new byte[size];
        rnd.NextBytes(b);
        return b;
    }
}

This gives me a output of:

27,65,24,105,94,143,119,226
27,65,24,105,94,143,119,226
26,64,23,104,93,142,118,225
26,64,23,104,93,142,118,225

This is bequase array is a reference type by assigning b2 you make a reference to a2 not a copy

CodePudding user response:

Thanks to all. I forget pointer.

   private void button22_Click(object sender, EventArgs e)
    {
        byte[] a2 = GetRandomArray(8);
        byte[] b2 = new byte[8];
        for (int x = 0; x < 8; x  )
        {
            b2[x] = a2[x];
            a2[x]=(byte)(a2[x] - 1);
            MessageBox.Show(a2[x].ToString()   "  |  "   b2[x].ToString());
        }

    }
  • Related