Jagged array explained

In computer science, a jagged array, also known as a ragged array [1] or irregular array [2] is an array of arrays of which the member arrays can be of different lengths,[3] producing rows of jagged edges when visualized as output. In contrast, two-dimensional arrays are always rectangular[4] so jagged arrays should not be confused with multidimensional arrays, but the former is often used to emulate the latter.

Arrays of arrays in languages such as Java, PHP, Python (multidimensional lists), Ruby, C#.NET, Visual Basic.NET, Perl, JavaScript, Objective-C, Swift, and Atlas Autocode are implemented as Iliffe vectors.

Examples

In C# and Java[5] jagged arrays can be created with the following code:[6] int[][]c;c = new int[2][]; // creates 2 rowsc[0] = new int[5]; // 5 columns for row 0c[1] = new int[3]; // create 3 columns for row 1

In C and C++, a jagged array can be created (on the stack) using the following code:

int jagged_row0[] = ;int jagged_row1[] = ;int *jagged[] = ;

In C/C++, jagged arrays can also be created (on the heap) with an array of pointers:

int *jagged[5];

jagged[0] = malloc(sizeof(int) * 10);jagged[1] = malloc(sizeof(int) * 3);

In C++/CLI, jagged array can be created with the code:[7] using namespace System;int main

In Fortran, a jagged array can be created using derived types with allocatable component(s):

type :: Jagged_type integer, allocatable :: row(:)end type Jagged_typetype(Jagged_type) :: Jagged(3)Jagged(1)%row = [1]Jagged(2)%row = [1,2]Jagged(3)%row = [1,2,3]

In Python, jagged arrays are not native but one can use list comprehensions to create a multi-dimensional list which supports any dimensional matrix:[8]

multi_list_3d = for i in range(3)] for i in range(3)]

  1. Produces:, [], []],, [], []],, [], []]]

multi_list_5d = for i in range(5)] for i in range(5)]

  1. Produces:, [], [], [], []],, [], [], [], []],, [], [], [], []],, [], [], [], []],, [], [], [], []]]

See also

Notes and References

  1. Book: King, K. N. . C Programming . W. W. Norton . 301 . 978-0-393-97950-3.
  2. Book: Handbook of Data Structures and Applications . CRC Press . 2004.
  3. Book: Jesse Liberty. Brian MacDonald. Learning C# 3.0. 18 November 2008. "O'Reilly Media, Inc.". 978-0-596-55420-0. 210–.
  4. Book: Don Box. Essential .Net: The Common Language Runtime. 2002. Addison-Wesley Professional. 978-0-201-73411-9. 138.
  5. News: Jagged Array in Java - GeeksforGeeks. 2016-02-03. GeeksforGeeks. 2018-08-13. en-US.
  6. Book: Paul J. Deitel. Harvey M. Deitel. C# 2008 for Programmers. 26 September 2008. Pearson Education. 978-0-13-701188-9. 40.
  7. Web site: Jagged Arrays. FunctionX. 26 November 2014.
  8. Web site: Lists in Python Demystified. Alvin.io. 31 January 2016.