Skip to content
Fix Code Error

How do I declare a 2d array in C++ using new?

March 13, 2021 by Code Error
Posted By: Anonymous

How do i declare a 2d array using new?

Like, for a “normal” array I would:

int* ary = new int[Size]

but

int** ary = new int[sizeY][sizeX]

a) doesn’t work/compile and b) doesn’t accomplish what:

int ary[sizeY][sizeX] 

does.

Solution

If your row length is a compile time constant, C++11 allows

auto arr2d = new int [nrows][CONSTANT];

See this answer. Compilers like gcc that allow variable-length arrays as an extension to C++ can use new as shown here to get fully runtime-variable array dimension functionality like C99 allows, but portable ISO C++ is limited to only the first dimension being variable.

Another efficient option is to do the 2d indexing manually into a big 1d array, as another answer shows, allowing the same compiler optimizations as a real 2D array (e.g. proving or checking that arrays don’t alias each other / overlap).


Otherwise, you can use an array of pointers to arrays to allow 2D syntax like contiguous 2D arrays, even though it’s not an efficient single large allocation. You can initialize it using a loop, like this:

int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
    a[i] = new int[colCount];

The above, for colCount= 5 and rowCount = 4, would produce the following:

enter image description here

Don’t forget to delete each row separately with a loop, before deleting the array of pointers. Example in another answer.

Answered By: Anonymous

Related Articles

  • Clang vs GCC - which produces faster binaries?
  • Where do I find the current C or C++ standard documents?
  • Why does C++ code for testing the Collatz conjecture…
  • Best practices for circular shift (rotate) operations in C++
  • [Vue warn]: Error in render: "TypeError: Converting…
  • react-table has a issue with rendering in next.js
  • How to sort an array in descending order in Ruby
  • Efficient Algorithm for Bit Reversal (from…
  • Maven2: Missing artifact but jars are in place
  • Combining items using XSLT Transform
  • How to change the default GCC compiler in Ubuntu?
  • C# parse FHIR bundle - read resources
  • Replacing a 32-bit loop counter with 64-bit…
  • How to install the Raspberry Pi cross compiler on my…
  • polymer + jquery gridster
  • Declare a variable to be instantiate at a class…
  • When is assembly faster than C?
  • How do I install soap extension?
  • #define macro for debug printing in C?
  • Laravel Livewire: Input select, default option selected
  • Uncaught TypeError: c.querySelectorAll is not a function
  • configure: error: C compiler cannot create executables
  • Can't find file executable in your configured search…
  • Aurelia UX showcase app fails to load
  • Adobe XD to responsive html
  • Java switch statement: Constant expression required,…
  • getting error while updating Composer
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Unresponsive hamburger icon in HTML
  • How to specify new GCC path for CMake
  • Using Auto Layout in UITableView for dynamic cell…
  • Aurelia CLI, babel runtime and async transforms
  • Why does the C preprocessor interpret the word…
  • Reset/remove CSS styles for element only
  • Why can't I get the value of asm registers in C?
  • Difference between `constexpr` and `const`
  • Debugging the error "gcc: error:…
  • Error message "Forbidden You don't have permission…
  • how to install gcc on windows 7 machine?
  • CMake error at CMakeLists.txt:30 (project): No…
  • Smart way to truncate long strings
  • Do I need to compile the header files in a C program?
  • How to add Typescript to a Nativescript-Vue project?
  • How to place object files in separate subdirectory
  • GCC: Array type has incomplete element type
  • Does C# have extension properties?
  • Text size and different android screen sizes
  • Auto-fit TextView for Android
  • What's the difference between __PRETTY_FUNCTION__,…
  • CSS grid wrapping
  • Difference between Fact table and Dimension table?
  • What is an application binary interface (ABI)?
  • How to prevent scrolling the whole page?
  • Fastest way to iterate over all the chars in a String
  • What's the difference between eval, exec, and compile?
  • Create a basic matrix in C (input by user !)
  • How to allocate aligned memory only using the…
  • How to disable GCC warnings for a few lines of code
  • For-each over an array in JavaScript
  • How do i arrange images inside a div?
  • Inline assembly statements in the variable…
  • How do I use arrays in C++?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • How to avoid a System.Runtime.InteropServices.COMException?
  • C++ : How can I parallelize an n-ary operation on n ranges?
  • Geolocation denied for HTML embedded site - anchor…
  • Is gcc's __attribute__((packed)) / #pragma pack unsafe?
  • How do I solve this error, "error while trying to…
  • Correct format specifier to print pointer or address?
  • In CSS Flexbox, why are there no "justify-items" and…
  • Tkinter scrollbar for frame
  • What is an IndexOutOfRangeException /…
  • How to remove item from array by value?
  • Polymer 1.0 'array-style' path accessors,…
  • Java Array, Finding Duplicates
  • Unable to specify the compiler with CMake
  • error: resource android:attr/fontVariationSettings not found
  • Convert utf8-characters to iso-88591 and back in PHP
  • RE error: illegal byte sequence on Mac OS X
  • Pointer-to-pointer dynamic two-dimensional array
  • Memcached vs. Redis?
  • Setting std=c99 flag in GCC
  • Having trouble with my nav bar/header, It used to…
  • Why can I not push_back a unique_ptr into a vector?
  • Compiling a C++ program with gcc
  • data.table vs dplyr: can one do something well the…
  • Wrong double initialization on Windows/MSYS2…
  • All com.android.support libraries must use the exact…
  • Convert Java Date to UTC String
  • htaccess "order" Deny, Allow, Deny
  • Create a new line in Java's FileWriter
  • R Code to Add a Special Header When Exporting a…
  • Keras input explanation: input_shape, units,…
  • C++ auto keyword. Why is it magic?
  • What's the difference between Instant and LocalDateTime?
  • Active tab issue on page load HTML
  • After a little scroll, the sticky navbar just is not…
  • Assembly Language - How to do Modulo?
  • Php - Your PHP installation appears to be missing…
  • POI Word Unable to merge newly created cell vertically

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

ValueError: setting an array element with a sequence

Next Post:

Why do I get AttributeError: ‘NoneType’ object has no attribute ‘something’?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error