Jump to content

Jagged array

From Wikipedia, the free encyclopedia

Template:Short description

numArr = [[1, 2, 3], [4, 5, 6, 7], [8, 9]]
Memory layout of a jagged array

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.

Jagged array can be implemented with Iliffe vector data structure in languages such as Java, PHP, Python (multidimensional lists), Ruby, C#.NET, Visual Basic.NET, Perl, JavaScript, Objective-C, Swift, and Atlas Autocode.

Examples

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

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

<syntaxhighlight lang="c"> int jagged_row0[] = {0,1}; int jagged_row1[] = {1,2,3}; int *jagged[] = { jagged_row0, jagged_row1 }; </syntaxhighlight>

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

<syntaxhighlight lang="c"> int *jagged[5];

jagged[0] = malloc(sizeof(int) * 10); jagged[1] = malloc(sizeof(int) * 3); </syntaxhighlight>

In C++/CLI, jagged array can be created with the code:[7] <syntaxhighlight lang="cpp"> using namespace System; int main() {

   array<array<double> ^> ^ Arrayname = gcnew array <array<double> ^> (4); // array contains 4 
   //elements
   return 0;

} </syntaxhighlight>

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

<syntaxhighlight lang="fortran"> type :: Jagged_type

   integer, allocatable :: row(:)

end type Jagged_type type(Jagged_type) :: Jagged(3) Jagged(1)%row = [1] Jagged(2)%row = [1,2] Jagged(3)%row = [1,2,3] </syntaxhighlight>

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]

<syntaxhighlight lang="python"> 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: [[[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]]

</syntaxhighlight>

See also

References

Template:Reflist

  1. ↑ Template:Cite book
  2. ↑ Template:Cite book
  3. ↑ Template:Cite book
  4. ↑ Template:Cite book
  5. ↑ Template:Cite news
  6. ↑ Template:Cite book
  7. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  8. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}