array in three dimensions

Is possible to make an array in three dimensions? If yes, how can i make one?
I tried this but it doesn't go, the compiler says "expected ';' before ')' token" at the line 8

#include<stdio.h>
int main(){
int matrix[2][2][2] = {0,1,2,3,4,5,6,7};
int i,j,k;
// Stampo i valori della matrice
for (i=0; i<2; i++)
for (j=0; j<2; j++)
for (k=0, k<2; k++)
printf ("Elemento in posizione [%d][%d][%d]: %d\n",i,j,k,matrix[i][j][k]);
}
Last edited on
You can make an array with any number of dimensions as long as that number is greater than 0 (and an integer). It is your initialiser list that is wrong here. When initialising a one dimensional array, you give a one dimensional list of parameters e.g.
int matrix[2] {0,1};
When initialising a two dimensional array, what you are making is an array of one dimensional arrays. If you are going to use arrayName[x][y] notation then think of it as a row of columns. Therefore the initalisation of a two dimensional array is like this.
int matrix[2][2] {{0,1},{2,3}} which when rearranged becomes this
1
2
3
4
5
6
 
int matrix[2][2]
{
    {0,1},
    {2,3}
}

This does look like a square, but it looks like a set of rows. Which is why if you are going to create an array like that, the accessing notation would often be matrix[yCoord][xCoord].
Therefore a 3 dimensional array is an array of two dimensional arrays (and array of arrays of arrays). It is therefore written like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int matrix[2][2][2]
{
    {
        {
            {0,1},
            {2,3}
        }
    },
    {
        {
            {4,5},
            {6,7}
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main()
{
    int matrix[2][2][2] = {{{0,1},{2,3}},{{4,5},{6,7}}};

    // Stampo i valori della matrice
    for (int i=0; i<2; i++)
    {
        for (int j=0; j<2; j++)
        {
            for (int k=0; k<2; k++)
            {
                cout << "Elemento in posizione " << i << " " << j << " " << k << " = " << matrix[i][j][k] << endl;
            }
        }
    }
    return 0;
}

Last edited on
Now i changed that one into this one but the compiler says the same error "expected ';' before ')' token"

#include<stdio.h>
int main(){
int matrix[2][2][2] = {{{0,1},{2,3}},{{4,5},{6,7}}};
int i,j,k;
// Stampo i valori della matrice
for (i=0; i<2; i++){
for (j=0; j<2; j++){
for (k=0, k<2; k++){
printf ("Elemento in posizione [%d][%d][%d]: %d\n",i,j,k,matrix[i][j][k]);
}
}
}
}
You have placed a comma after k=0
for (k=0, k<2; k++)
It should be a semicolon.

oh my god, i'm so stupid. thanks
Topic archived. No new replies allowed.