0

I am learning was try to print out result from multi-dimensional array. My code is

int numbers[3][3][4] = 
{
    { 
        {5,3,8,7},
        {1,2,3,4},
        {8,9,10,11} 
    },
    {
        {12,13,14,15},
        {16,17,18,19},
        {20,21,22,23}
    },
    {
        {121,131,141,151},
        {161,171,181,119},
        {210,211,212,213}
    }
};
int i,j,k;
// int arraylength = sizeof(numbers)/sizeof(int);
// cout<<arraylength;
for(i=0;i<=3;i++){
        for(j=0;j<=3;j++){
         for(k=0;k<=4;k++){
            cout<<numbers[i][j][k];
            }
            cout<<endl;
        }
    }   
return 0;
}

I am trying to get output the number but getting negative number. also i was trying to get the length of the array to work with the loop with

int arraylength = sizeof(numbers)/sizeof(int);

with this i am getting the whole length of the array but how i can get the nested array length??

  • Please use `<` not `<=`. – GAVD Oct 13 '22 at 04:10
  • 1
    `for(i=0;i<=3;i++){` -- This is an out-of-bounds access, and the same with all of the other `for` loops. Using `<=` for a loop condition is an indication of this. Array indices go from 0 to `n-1`, where `n` is the number of elements. Closing as a typo, as the correct condition would use `<`. – PaulMcKenzie Oct 13 '22 at 04:11
  • 1
    Note that range-based loops work on primitive array types, so you can potentially save yourself some headaches for a simple program like this: https://godbolt.org/z/68sE65cE1 – paddy Oct 13 '22 at 04:20
  • Thankyou Paul and Paddy – Coder Shashank Naithani Oct 18 '22 at 17:50

1 Answers1

0
  1. Indices of arrays in C++ (and C) are 0..(n-1), where n is the number of elements.
    Therefore your loops should use < instead of <= (to avoid accessing memory out of bounds):
for(i=0;i<3;i++){
    for(j=0;j<3;j++){
        for(k=0;k<4;k++){
            // ...
        }
    }
}
  1. In order to get the size of the nested arrays, you can use:
std::cout << sizeof(numbers[0]) << std::endl;
std::cout << sizeof(numbers[0][0]) << std::endl;

Output:

48
16

Side notes:

  1. In c++ it is usually recomended to use std::vector instead of raw C arrays. In order to manage multidimentional arrays I always prefer to keep a 1D std::vector, and manage the indices manually. Look for strided arrays for more details. You can see an example for 2D in my answer here: Two-dimensional dynamic array pointer access.
  2. Better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
wohlstad
  • 12,661
  • 10
  • 26
  • 39