Home > OS >  Addresses of values in an array aren't static C#
Addresses of values in an array aren't static C#

Time:09-15

So, I am currently making a little code with some pointers. I am trying to get every values of an array, and their respective address. However, the initial array is empty, and the user has to enter numbers as an input, which ends up being added to the array itself. Then, I want to get the address of each value that the user added, one by one. Everything works fine, except one thing; I want every value to have a static address. However, I noticed that at every inputs, every values had a different address than the one they had before. I tried to put the array as a global static variable, but it still doesn't work. Any help?

Thanks for everyone who takes their time to answer! <3

Full code:

using System;

public class ClearIt
{
   public int k = 8;
}

public static class Arr
{
    public static int StaticAddress;
    public static int[] x = { };
}

public class Class
{
    public static unsafe void Main()
    {
        ClearIt clearIt = new ClearIt();

        int k2 = clearIt.k;

        for (int j = 0; j < 1;)
        {
           string Read = Console.ReadLine();

         int ReadToInt;

            bool isTrue;

            isTrue = int.TryParse(Read, out ReadToInt);
            if (!isTrue)
            {
                return;
            }
           int StaticAdd = Arr.StaticAddress = ReadToInt;
            if (k2 > 0)
            {
                var xList = Arr.x.ToList();
                xList.Add(StaticAdd);
                Arr.x = xList.ToArray();
                Array.Sort(Arr.x);
                k2--;
            }
            
            else if(k2 == 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;

                var xList2 = Arr.x.ToList();
                    xList2.Clear();
                Arr.x = xList2.ToArray();
                Console.WriteLine("Array cleared.");
                Console.ForegroundColor = ConsoleColor.White;
                k2 = 8;
            }

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("\nValues\tAddresses");

            for (int i = 0; i < Arr.x.Length; i  )
            {
                fixed (int* y = &Arr.x[i])
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("\n"   *y   $"\t{(long)y:X}\n");
                    Console.ForegroundColor = ConsoleColor.White;
                }
            }
        }
    }
}

CodePudding user response:

The short answer is that everytime you assign to Arr.x you are creating a new array and a new part of memory is used.

The statement below for example causes Arr.x address to change

Arr.x = xList2.ToArray();

If you do not want to change the address of Arr.x, then only assign it once to the maximum length, and keep track of the item count actually stored.

My best guess is that you are trying to do something like this

fig1

where the addresses in memory do not change when items are added or the array is cleared. After the 8th number is added, the list clears

fig3

and more numbers can be added

fig2

As you can see the address value does not change.

I am using fixed buffer arrays to store the values, instead of the regular array. Here is the code that generates the output above

class Program
{
    static void Main(string[] args)
    {
        var arr = new FixedArray();

        do
        {
            Console.Clear();

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine($"{"offset"}\t{"address"}\t{"value"}");
            for (int i = 0; i < arr.Count; i  )
            {
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write($"{i}");
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write($"\t{arr.GetItemAddress(i)}");
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine($"\t{arr[i]:X}");
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            if (arr.Count == 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Array Cleared.");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine();
            }

            Console.WriteLine("Enter Value:");
            string input = Console.ReadLine();
            if (int.TryParse(input, out int value))
            {
                if (arr.Add(value))
                {
                }
                else
                {
                    arr.Clear();
                }
            }
            else
            {
                return;
            }
            
        } while (true);
    }
}

and FixedArray is the object that actually stores the data

public unsafe struct FixedArray
{
    public const int Size = 8;
    fixed int data[Size];

    public FixedArray(params int[] array) : this()
    {
        Count = Math.Min(Size, array.Length);
        fixed (int* ptr = data)
        {
            for (int i = 0; i < Count; i  )
            {
                ptr[i] = array[i];
            }
        }
    }

    public IntPtr GetItemAddress(int offset = 0)
    {
        fixed (int* ptr = &data[offset])
        {
            return (IntPtr)ptr;
        }
    }
    public int this[int offset]
    {
        get
        {
            if (offset >= 0 && offset < Count)
            {
                return data[offset];
            }
            return 0;
        }
    }
    public int Count { get; private set; }
    public void Clear() { Count = 0; }
    public bool Add(int x)
    {
        if (Count < Size)
        {
            data[Count] = x;
            Count  ;
            return true;
        }
        return false;
    }
    public int[] ToArray()
    {
        int[] array = new int[Count];
        fixed (int* ptr = data)
        {
            for (int i = 0; i < Count; i  )
            {
                array[i] = ptr[i];
            }
        }
        return array;
    }
}
  • Related