Tristan McPherson
Tristan McPherson

Reputation: 367

Array values not changing?

For some reason, this doesn't edit the size of the array inputted into it, and the data isn't added to the array inputted.

    public static void RandomizeArray(int[] array)
    {
        int intRead;
        int intReadSeed;
        Random randomNum = new Random();
        Console.WriteLine("How many ints do you want to randomly generated?");
        intRead = Convert.ToInt32(Console.ReadLine());
        array = new int[intRead];
        Console.WriteLine("What's the maximum value of the randomly generated ints?");
        intReadSeed = Convert.ToInt32(Console.ReadLine());
        for (int i = 0; i < intRead; i++)
        {
            array[i] = (randomNum.Next(intReadSeed));
        }
        Console.WriteLine("Randomization Complete.\n");
    }

Upvotes: 1

Views: 2072

Answers (2)

Patashu
Patashu

Reputation: 21773

When you pass array to this method, you pass it by value - that is, you make a brand new variable that ALSO points to the same object. If you edit the variable array in your method to point to a new array, it doesn't also make the other variable point to your new array - it still points to the old array. So when you return you haven't done any edits to the array that was passed in.

To fix this, return array; at the end of the method, and change the signature from void to int[]. Or you can do out int[] array as the parameter, so you pass by reference and edit over it.

Upvotes: 6

Dustin Kingen
Dustin Kingen

Reputation: 21245

Simple fix declare the parameter as out.

public static void RandomizeArray(out int[] array)
{
    int intRead;
    int intReadSeed;
    Random randomNum = new Random();

    Console.WriteLine("How many ints do you want to randomly generated?");

    intRead = Convert.ToInt32(Console.ReadLine());
    array = new int[intRead];

    Console.WriteLine("What's the maximum value of the randomly generated ints?");
    intReadSeed = Convert.ToInt32(Console.ReadLine());

    for (int i = 0; i < intRead; i++)
    {
        array[i] = (randomNum.Next(intReadSeed));
    }

    Console.WriteLine("Randomization Complete.\n");
}

That way you can call it:

int[] array;

RandomizeArray(out array);

However, it would probably be better to simply return an array.

public static int[] GenerateRandomizedArray()
{
    int intRead;
    int intReadSeed;
    Random randomNum = new Random();

    Console.WriteLine("How many ints do you want to randomly generated?");
    intRead = Convert.ToInt32(Console.ReadLine());
    var array = new int[intRead];

    Console.WriteLine("What's the maximum value of the randomly generated ints?");
    intReadSeed = Convert.ToInt32(Console.ReadLine());

    for (int i = 0; i < intRead; i++)
    {
        array[i] = (randomNum.Next(intReadSeed));
    }

    Console.WriteLine("Randomization Complete.\n");

    return array;
}

Upvotes: 3

Related Questions