Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do jagged arrays exist in C/C++?

Is there such a thing as a jagged array in C or C++?

When I compile this:

int jagged[][] = { {0,1}, {1,2,3} }; 

I get this error:

error: declaration of `jagged' as multidimensional array must have bounds for all dimensions except the first

like image 312
unknown Avatar asked Jul 05 '09 08:07

unknown


People also ask

How do you declare a jagged array in C sharp?

A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays. jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2]; Each of the elements is a single-dimensional array of integers.

What is difference between array and jagged array?

In a multidimensional array, each element in each dimension has the same, fixed size as the other elements in that dimension. In a jagged array, which is an array of arrays, each inner array can be of a different size.

Where are jagged arrays used?

Jagged arrays are a special type of arrays that can be used to store rows of data of varying lengths to improve performance when working with multi-dimensional arrays. An array may be defined as a sequential collection of elements of the same data type.

Are jagged arrays 2D arrays?

A jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These types of arrays are also known as Jagged arrays.


2 Answers

In C I would use an array of pointers.

For instance:

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

etc etc.

like image 95
Cromulent Avatar answered Oct 03 '22 18:10

Cromulent


There's a bunch of ways to do it. Here's another way:

int jagged_row0[] = {0,1}; int jagged_row1[] = {1,2,3}; int *jagged[] = { jagged_row0, jagged_row1 }; 
like image 27
rampion Avatar answered Oct 03 '22 18:10

rampion