Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm trying to create an empty 2d/multidimensional array and then add data to it at specific indexes. Can someone tell me where I'm going wrong?

Struggling to add data to a specific index of a 2D array. I’m quite new to programming so I could have this all completely wrong but any help would be appreciated.

Maybe my declaration of the array is wrong but I am seeing the first pair of [] as the first part where data can be stored, and then the second set inside the first [] is another place where I can store data and this data is linked to the data in the first pair of []

I’m very sorry if I’m not explaining this properly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void main(){
  var staff = [[]];
  
  int a = 1;
  int b = 2;
    
  staff[0][0].add(b)
  staff[0][1].add(a)
  staff[1][0].add(b)
  staff[1][1].add(a)
  
  print(staff);
}

Ideally I would like an output that looks something like this

[2,1][2,1]

Cheers 😀

>Solution :

Dart is not JavaScript. Arrays (Lists) are not automatically grown when accessing out-of-bounds elements. You must explicitly grow your Lists to have the desired lengths:

void main() {
  var staff = [
    for (var i = 0; i < 2; i += 1)
      [
        for (var j = 0; j < 2; j += 1) 0,
      ],
  ];

  int a = 1;
  int b = 2;

  staff[0][0] = b;
  staff[0][1] = a;
  staff[1][0] = b;
  staff[1][1] = a;

  print(staff); // Prints: [[2, 1], [2, 1]]
}

Alternatively, if you want to grow your Lists dynamically:

void main() {
  var staff = <List<int>>[];

  int a = 1;
  int b = 2;

  staff.add([b, a]);
  staff.add([b, a]);

  print(staff); // Prints: [[2, 1], [2, 1]]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading