how to inset a new array to my jagged array

前端 未结 1 1454
一生所求
一生所求 2021-01-25 12:26

hello i will much apreciate any help.

ok let\'s see, first i have declare a jagged array like this and the next code

int n=1, m=3,p=0;

int[][] jag_array         


        
1条回答
  •  南笙
    南笙 (楼主)
    2021-01-25 12:53

    The size of an array, once created, is by definition invariable. If you need a variable number of elements, use a List - in your case, probably a List.

    The only alternative solution would be to created a new array with the new size (and assign that to your jag_array variable) and copy all the previous elements from your old array into the new array. That is unnecessarily complicated code when you can just use List, but if you cannot use List for any reason, here is an example:

    // increase the length of jag_array by one
    var old_jag_array = jag_array; // store a reference to the smaller array
    jag_array = new int[old_jag_array.Length + 1][]; // create the new, larger array
    for (int i = 0; i < old_jag_array.Length; i++) {
        jag_array[i] = old_jag_array[i]; // copy the existing elements into the new array
    }
    jag_array[jag_array.Length - 1] = ... // insert new value here
    

    0 讨论(0)
提交回复
热议问题