CTOverton
CTOverton

Reputation: 686

Manually setting values in 2Darrays C++

Simply put an array can be defined with

int arrayValues = {1,2,3,4,5};

How do you define in a similar manor with a double array to avoid writing this out...

int magicArray[rowSize][colSize];

magicArray[0][0] = 4;
magicArray[0][1] = 3;
magicArray[0][2] = 8;

magicArray[1][0] = 9;
magicArray[1][1] = 5;
magicArray[1][2] = 1;

magicArray[2][0] = 2;
magicArray[2][1] = 7;
magicArray[2][2] = 6;

Is it possible to write something like...

int magicArray[rowSize][colSize] = { {x,y,value}, {0,0,1}} 

Upvotes: 0

Views: 20

Answers (1)

SunKnight0
SunKnight0

Reputation: 3351

A two dimensional array is the same as a one dimensional array in memory. They are both just pointers. Create your array as one-dimensional, initialize it, then create your two dimensional array and point it to the same pointer.

I do not have a testing environment handy and have not worked with C++ in a while so use this with caution and just as a starting point:

int tempArray[rowSize*colSize]={4,3,8,9,5,1,2...};
int magicArray[rowSize][colSize];
magicArray=tempArray;

Upvotes: 1

Related Questions