I wanted to declare a 2D array and assign values to it, without running a for loop.
I thought I could used the following idea
int array[5] = {1,2,3,4,5};   Which works fine to initialize the 2D array as well. But apparently my compiler doesn't like this.
/*  1   8  12  20  25  5   9  13  24  26 */  #include <iostream.h>  int main() {     int arr[2][5] = {0};   // This actually initializes everything to 0.     arr [1] [] = {1,8,12,20,25}; // Line 11     arr [2] [] = {5,9,13,24,26};     return 0; }   J:\CPP\Grid>bcc32.exe Grid.cpp
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
Grid.cpp:
Error E2188 Grid.cpp 11: Expression syntax in function main()
Error E2188 Grid.cpp 12: Expression syntax in function main()
Warning W8004 Grid.cpp 14: 'arr' is assigned a value that is never used in funct ion main()
* 2 errors in Compile *
Please help as to what is the right way to initialize the 2d array with my set of values.
A two-dimensional array in C can be thought of as a matrix with rows and columns. The general syntax used to declare a two-dimensional array is: A two-dimensional array is an array of several one-dimensional arrays. Following is an array with five rows, each row has three columns: int my_array[5][3];
Here i and j are the size of the two dimensions, i.e I denote the number of rows while j denotes the number of columns. Example: int A[10][20]; Here we declare a two-dimensional array in C, named A which has 10 rows and 20 columns.
An array of arrays is known as 2D array. The two dimensional (2D) array in C programming is also known as matrix. A matrix can be represented as a table of rows and columns.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With