1

I need to create a 2D array where size of column is fixed as 6 but size of row may vary . How to give dynamic row size in 2D array ? Below is the code I tried but no luck.

int n;
string num = console.ReadLine();
Int32.TryParse(num,out n);
int[,] ar = new int[n,6] ;
3
  • What is the problem with your code? Commented Mar 16, 2016 at 18:37
  • 2
    You have a typo: Console should be capitalized. What do you mean by "no luck"? Did the code compile? After changing the capitalization of Console I was able to run it successfully. Commented Mar 16, 2016 at 18:38
  • stackoverflow.com/questions/683073/… Commented Mar 16, 2016 at 18:39

2 Answers 2

1

There's nothing wrong with the way you're constructing the mulitidimentional array. The following code is valid so I suspect your error is somewhere else:

int n = 9;
int[,] ar = new int[n,6];

I'm guessing your input is not coming through correctly so add some error checks to figure out what went wrong. First, Console.ReadLine() has to be capitalized or it wont compile. Next, make sure TryParse is actually functioning properly (it returns a bool indicating success or failure:

int n;
string num = Console.ReadLine();
if (num == null) {
    // ERROR, No lines available to read.
}
if (!Int32.TryParse(num,out n)) {
    // ERROR, Could not parse num.
}
int[,] ar = new int[n,6];

If issues persist, people generally appreciate more descriptive explanations than "I tried but no luck." Make sure to inform people viewing your question that it was a compilation error or a runtime error and be as specific as you can.

Sign up to request clarification or add additional context in comments.

Comments

0

I would use a Dictionary as so.

Dictionary<int,List<int>> numbers = new Dictionary<int,List<int>>();

And you could add an item like this:

numbers.Add(1,new List<int>(){1,2,3,4,5,6});

And to add numbers to a particular row.

numbers[1].Add(7);

And to access a number in a specific row and column.

numbers[1][2] = 34;

2 Comments

Collection classes are great but a Dictionary would involve far more overhead than most other solutions.
True, it was just the first thing I thought of for this rather unusual request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.