Search code examples
c#classquicksort

Having trouble creating random values


So I created Pairs class that contains int and double and I want to create an array of them with my array class by creating random values, but I'm getting System.NullReferenceException at Line 19 of my array class.

Here's my pair class

class Pair
{

    public int integer = 0;
    public double doubl = 0.0;

    public Pair(int integer, double doubl)
    {
        this.integer = integer;
        this.doubl = doubl;
    }

    public Pair()
    {

    }
    public int Integer() { return integer; }
    public double Doubl() { return doubl; }
}

And this is my array class and the abstract class

class MyDataArray : DataArray
{

    Pair[] data;
    int operations = 0;

    public MyDataArray(int n, int seed)
    {
        data = new Pair[n];
        Random rand = new Random(seed);
        for (int i = 0; i < n; i++)
        {
            data[i].integer = rand.Next(); //I get error here
            data[i].doubl = rand.NextDouble();

        }

    }

    public int integer(int index)
    {
        return data[index].integer;

    }

    public double doubl(int index)
    {
        return data[index].doubl;
    }
}

abstract class DataArray
{

    public int operations { get; set; }
    public abstract void Swap(int i, int j);
    public abstract void Swap2(int i, int high);
}

Also is it even worth it using this abstract class I used this from a reference that my university provided. I have to create an quicksort algorithm that sorts pairs in arrays and linked lists and analyze it.


Solution

  • The issue with your code is that you are only initializing the array of data in MyDataArray. When creating an array of instances, it only initializes references for the array, not the actual instances to be in the array. Those references all point to null. So when you do try to set the integer member of the i'th Pair instance in the data array:

    ...
    data[i].integer = rand.Next();
    ...
    

    You are actually trying to set the integer member of null, which does not exist.

    ...
    null.integer = rand.Next();
    ...
    

    To fix this, simply create a new instance of Pair for each index of data in your loop.

    ...
    for (int i = 0; i < n; i++)
    {
        data[i] = new Pair();
        data[i].integer = rand.Next();
        data[i].doubl = rand.NextDouble();
    
    }
    ...
    

    Even better, you can use the constructor you've made where it takes parameters to set integer and doubl upon construction to simplify the code in your loop.

    ...
    for (int i = 0; i < n; i++)
    {
        data[i] = new Pair(rand.Next(), rand.NextDouble());
    }
    ...