[c++] 2D array values C++

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.

This question is related to c++ c multidimensional-array initialization shortcut

The answer is


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.


One alternative is to represent your 2D array as a 1D array. This can make element-wise operations more efficient. You should probably wrap it in a class that would also contain width and height.

Another alternative is to represent a 2D array as an std::vector<std::vector<int> >. This will let you use STL's algorithms for array arithmetic, and the vector will also take care of memory management for you.


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;
}

int iArray[2][2] = {{1, 2}, {3, 4}};

Think of a 2D array as an array of arrays.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to multidimensional-array

what does numpy ndarray shape do? len() of a numpy array in python What is the purpose of meshgrid in Python / NumPy? Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray Typescript - multidimensional array initialization How to get every first element in 2 dimensional list How does numpy.newaxis work and when to use it? How to count the occurrence of certain item in an ndarray? Iterate through 2 dimensional array Selecting specific rows and columns from NumPy array

Examples related to initialization

"error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to declare an ArrayList with values? Initialize array of strings Initializing a dictionary in python with a key value and no corresponding values Declare and Initialize String Array in VBA VBA (Excel) Initialize Entire Array without Looping Default values and initialization in Java Initializing array of structures C char array initialization

Examples related to shortcut

Collapse all methods in Visual Studio Code How do I create a shortcut via command-line in Windows? window.close() doesn't work - Scripts may close only the windows that were opened by it How to automatically generate getters and setters in Android Studio How to update gradle in android studio? Is there a short cut for going back to the beginning of a file by vi editor? How to create a shortcut using PowerShell How do I call a function twice or more times consecutively? Eclipse comment/uncomment shortcut? 2D array values C++