NoahGav
NoahGav

Reputation: 271

How to initialize a multidimensional array in c++?

I want to make an array and set values to it some what like this double MyArray[][] = {{0.1,0.8},{0.4,0.6},{0.3,0.9}}. I don't however want to do this MyArray[0][0] = 0.1; MyArray[0,1] = 0.8; MyArray[1][0] = 0.4;ect, But I don't know how to do this. Thanks in advance for any help :) .

Upvotes: 1

Views: 55

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

It is enough to write

double MyArray[][2] = {{0.1,0.8},{0.4,0.6},{0.3,0.9}};
                ^^^

A two-dimensional array is a one-dimensional array elements of which are in turn arrays. When an array is created the size of its elements shall be known.

You can imagine this the following way

typedef double T[2];

//..

T MyArray[] = {{0.1,0.8},{0.4,0.6},{0.3,0.9}};

As for these statements

MyArray[0][0] = 0.1; MyArray[0,1] = 0.8; MyArray[1][0] = 0.4;

then if you would declare the array like this

#include <array>

//...

std::array<double, 2> MyArray[3];

You could write

MyArray[0] = { 0.1, 0.8 };
MyArray[1] = { 0.4, 0.6 };
MyArray[2] = { 0.3, 0.9 };

Upvotes: 3

Edward Strange
Edward Strange

Reputation: 40897

You need to at least tell the compiler what the inner dimension is:

double MyArray[][2] = {{.1, .8},{.4, .6} /* etc... */ };

Upvotes: 2

Related Questions