2D array values C++ 2D array values C++ c c

2D array values C++


Like this:

int main(){    int arr[2][5] =    {        {1,8,12,20,25},        {5,9,13,24,26}    };}

This should be covered by your C++ textbook: which one are you using?

Anyway, better, consider using std::vector or some ready-made matrix class e.g. from Boost.


The proper way to initialize a multidimensional array in C or C++ is

int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};

You can use this same trick to initialize even higher-dimensional arrays if you want.

Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!


Just want to point out you do not need to specify all dimensions of the array.

The leftmost dimension can be 'guessed' by the compiler.

#include <stdio.h>int main(void) {  int arr[][5] = {{1,2,3,4,5}, {5,6,7,8,9}, {6,5,4,3,2}};  printf("sizeof arr is %d bytes\n", (int)sizeof arr);  printf("number of elements: %d\n", (int)(sizeof arr/sizeof arr[0]));  return 0;}