How to Define a Two-Dimensional Array

How to define a two-dimensional array?

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this
"list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)]

#You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

How can I create a two dimensional array in JavaScript?

var items = [  [1, 2],  [3, 4],  [5, 6]];console.log(items[0][0]); // 1console.log(items[0][1]); // 2console.log(items[1][0]); // 3console.log(items[1][1]); // 4console.log(items);

What is the best way to make 2 dimensional array in C

This

int **arr = (int **)malloc(sizeof(int *) * 3);

is not a declaration or allocation of a two-dimensional array

Here a one-dimensional array with the element type int * is created. And then each element of the one-dimensional array in turn points to an allocated one dimensional array with the element type int.

This declaration of a two-dimensional array

    const int row = 3;
const int col = 4;

int arr[row][col] = {
{1,2,3,4},
{3,4,5,6},
{5,6,7,8}
};

is incorrect. Variable length arrays (and you declared a variable length array) may not be initialized in declaration.

You could write instead

    enum { row = 3, col = 4 };

int arr[row][col] = {
{1,2,3,4},
{3,4,5,6},
{5,6,7,8}
};

When such an array is passed to a function it is implicitly converted to pointer to its first element of the type int ( * )[col].

You could pass it to a function that has a parameter of the type of a variable length array the following way

void    my_func( size_t row, size_t col, int arr[row][col] )
{
printf("test2: %d", arr[0][1]);
}

Or if to place the definition of the enumeration before the function declaration

    enum { row = 3, col = 4 };

then the function could be also declared like

void    my_func( int arr[][col], size_t row )
{
printf("test2: %d", arr[0][1]);
}

Here is a demonstrative program that shows three different approaches. The first one when an array is defined with compile-time constants for array sizes. The second one when a variable length array is created. And the third one when a one-dimensional array of pointer to one-dimensional arrays are allocated dynamically.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum { row = 3, col = 4 };

void output1( int a[][col], size_t row )
{
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
printf( "%d ", a[i][j] );
}
putchar( '\n' );
}
}

void output2( size_t row, size_t col, int a[row][col] )
{
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
printf( "%d ", a[i][j] );
}
putchar( '\n' );
}
}

void output3( int **a, size_t row, size_t col )
{
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
printf( "%d ", a[i][j] );
}
putchar( '\n' );
}
}


int main(void)
{
int arr1[row][col] =
{
{1,2,3,4},
{3,4,5,6},
{5,6,7,8}
};

output1( arr1, row );
putchar( '\n' );

const size_t row = 3, col = 4;

int arr2[row][col];

memcpy( arr2, arr1, row * col * sizeof( int ) );

output2( row, col, arr2 );
putchar( '\n' );

int **arr3 = malloc( row * sizeof( int * ) );

for ( size_t i = 0; i < row; i++ )
{
arr3[i] = malloc( col * sizeof( int ) );
memcpy( arr3[i], arr1[i], col * sizeof( int ) );
}

output3( arr3, row, col );
putchar( '\n' );

for ( size_t i = 0; i < row; i++ )
{
free( arr3[i] );
}

free( arr3 );
}

The program output is

1 2 3 4 
3 4 5 6
5 6 7 8

1 2 3 4
3 4 5 6
5 6 7 8

1 2 3 4
3 4 5 6
5 6 7 8

Pay attention to that the function output2 can be used with the array arr1 the same way as it is used with the array arr2.

Declare an empty two-dimensional array in Javascript?

You can just declare a regular array like so:

var arry = [];

Then when you have a pair of values to add to the array, all you need to do is:

arry.push([value_1, value2]);

And yes, the first time you call arry.push, the pair of values will be placed at index 0.

From the nodejs repl:

> var arry = [];
undefined
> arry.push([1,2]);
1
> arry
[ [ 1, 2 ] ]
> arry.push([2,3]);
2
> arry
[ [ 1, 2 ], [ 2, 3 ] ]

Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:

> arry.push(100);
3
> arry
[ [ 1, 2 ],
[ 2, 3 ],
100 ]

How to use a two dimensional array in function declaration statement?

The prototype

void mat(int [][],int [][],int ,int);  

should be

void mat(int [][10],int [][10],int ,int);  

You must have to specify the higher dimensions. Other way around, the above prototype is equivalent to

void mat(int (*)[10],int (*)[10],int ,int);  

int (*)[10] is a type (pointer to an array of 10 int) and without size 10 it is of incomplete type.

How do I declare a 2d array in C++ using new?

If your row length is a compile time constant, C++11 allows

auto arr2d = new int [nrows][CONSTANT];

See this answer. Compilers like gcc that allow variable-length arrays as an extension to C++ can use new as shown here to get fully runtime-variable array dimension functionality like C99 allows, but portable ISO C++ is limited to only the first dimension being variable.

Another efficient option is to do the 2d indexing manually into a big 1d array, as another answer shows, allowing the same compiler optimizations as a real 2D array (e.g. proving or checking that arrays don't alias each other / overlap).


Otherwise, you can use an array of pointers to arrays to allow 2D syntax like contiguous 2D arrays, even though it's not an efficient single large allocation. You can initialize it using a loop, like this:

int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
a[i] = new int[colCount];

The above, for colCount= 5 and rowCount = 4, would produce the following:

Sample Image

Don't forget to delete each row separately with a loop, before deleting the array of pointers. Example in another answer.

declaring two-dimensional array

2-dimensional array is correct. First index is column, second index is row.

Dim strData(,) As String 'Use String variable type, even for the numbers
Dim intRowCount As Integer = 5
Dim intColumnCount As Integer = 3
ReDim strData(intColumnCount - 1, intRowCount - 1) 'subtract 1 because array indices are 0-based. Column 0 = Range start, Column 1 = Range End, Column 2 = Grade
'first row
strData(0, 0) = "0" 'Range start
strData(1, 0) = "299" 'Range end
strData(2, 0) = "F" 'Grade
'second row
strData(0, 1) = "300"
strData(1, 1) = "349"
strData(2, 1) = "D"
'third row
strData(0, 2) = "350"
strData(1, 2) = "399"
strData(2, 2) = "C"
'fourth row
strData(0, 3) = "400"
strData(1, 3) = "449"
strData(2, 3) = "B"
'fifth row
strData(0, 4) = "450"
strData(1, 4) = "500"
strData(2, 4) = "A"
'Add a row
intRowCount = intRowCount + 1
ReDim Preserve strData(intColumnCount - 1, intRowCount - 1)
'sixth row
strData(0, 5) = "501"
strData(1, 5) = "600"
strData(2, 5) = "A+"

Note that Redim Preserve can only change the last index in the array, which is why we store in (column, row) order rather than the more traditional (row, column) order.

How to create two dimensional array in Promela?

From the docs:

Multidimensional arrays can be constructed indirectly with the use of typedef definitions.

Also from the docs:

EXAMPLES

The first example shows how to declare a two-dimensional array of elements of type byte with a typedef.

typedef array { /* typedefs must be global */
byte aa[4]
};
init {
array a[8]; /* 8x4 = 32 bytes total */
a[3].aa[1] = 5
}

A better approach is to use one-dimensional arrays.

How to declare initialize and use 2 dimensional arrays in Java Script Using a text from html page

There is no "matrix" structure natively in the language. But you can create them without major problem as far as you "book" the required memory.

Let's say you would like to create a 3x3 matrix, first you have to create an Array which will store references to each row/column (depending of your point of view, of course).

function createMatrix(N, M) {
var matrix = new Array(N); // Array with initial size of N, not fixed!

for (var i = 0; i < N; ++i) {
matrix[i] = new Array(M);
}

return matrix;
}


Related Topics



Leave a reply



Submit