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
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.
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.
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.
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.
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.
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With