There was a problem while changing the c# array

Asked 2 years ago, Updated 2 years ago, 40 views

int[] Heap = new int[4];

for(int i=0;i<32;i++)
{
     if(usedsize == Heap.Length) //
        {
            Array.Resize(ref Heap, Heap.Length *2);    
            Console.WriteLine("Heap["+(Heap.Length-1)+"] ="+Heap[Heap.Length-1]);
        }
    ++usedsize; 
  } //Output: Heap[7] = 0


Above code, Array if array is full.Resize to double the maximum capacity of the array Not the first time. Heap.Length is changed from 4 to 8 only at the first time. After that, in 8, the if statement doesn't become true Implementation is Heap.You can point to a variable that points to the last value without using Length Why is heap like this?I wonder if the value of the length is not changed.

c#

2022-09-22 18:42

1 Answers

using System;
public class Hello1 {
    public static void Main() {
        int[] Heap = new int[4];
        int usedsize = 0;

        for(int i=0;i<32;i++)
        {
            if(usedsize == Heap.Length) //
            {
                Array.Resize(ref Heap, Heap.Length *2);    
                Console.WriteLine("Heap["+(Heap.Length-1)+"] ="+Heap[Heap.Length-1]);
            }
            ++usedsize; 
        } 
    }
}
Heap[7] =0
Heap[15] =0
Heap[31] =0

The code you posted is simple and working well, so it's hard to find a problem.

Try tracking by step in debugging mode.


2022-09-22 18:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.