1d and 2d dynamic arrays

hey everyone,
I was wondering if I can add fixed values to a 1d or 2d dynamic array like static ones. For instance

int arr[4] = {0, 1, 2, 3}; <-- that's static

but I want to do the same thing using a 1d and a 2d dynamic array but I stop here

int* arr = new int[4];
arr[4] = {0, 1, 2, 3}; <-- this is not correct

Same with 2d dynamic arrays. May I please know the correct way of doing this?

Thanks
you can have this idea with vectors, which use dynamic arrays inside.
that is the better way, but
int *array = new int[5] { 9, 7, 5, 3, 1 }; // initialize a dynamic array since C++11
1
2
3
4
5
auto arr = new int[4] { 0, 1, 2, 3 } ;
delete[] arr ;

auto arr_2d = new int[3][4] { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 } } ;
delete[] arr_2d ;

@jonnin and @JLBorges
Thank you so much
If this is truly a "dynamic" 2-d array, why is A2d accepted below, but B2d not?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int main()
{
   int n = 4;
      
   auto a1d = new int[4];         // OK
   delete[] a1d;
   
   auto b1d = new int[n];         // OK
   delete[] b1d;
    
    
   auto A2d = new int[4][4];      // OK, but new doesn't seem necessary
   delete[] A2d;

   auto B2d = new int[n][n];      // not legitimate
   delete[] B2d;
   
   
   auto C2d = new int*[n];
   for ( int i = 0; i < n; i++ ) C2d[i] = new int[n];  // OK, but painful
   for ( int i = 0; i < n; i++ ) delete C2d[i];
   delete [] C2d;
}
Last edited on
If this is truly a "dynamic" 2-d array, why is A2d accepted below, but B2d not?
Are you asking the OP or do you want to know it?
Hi @coder777, it was for my own interest (in response to @JLBorges' post), so if you can give an explanation I'd appreciate it.

I had been used to allocating 2-d array memory in the way that I had done for C2d (on the rare occasions that I use it - I usually prefer to flatten to 1-d arrays for MPI transfers etc.) I was surprised that @JLBorges' solution worked, but then equally surprised that it didn't then work for run-time array bounds. There doesn't seem much purpose in using new for fixed array sizes, other than access to large amounts of heap space.
Last edited on
The reason why the first expression works and the second not is bascially the same why foo(...) works and bar(...) not:
1
2
3
4
5
6
7
8
9
void foo(int a[][4]) // Ok
{
...
}

void bar(int a[][]) // Error
{
...
}
The compiler needs one fixed field size to calculate the index.

This works:
1
2
  int n = 4;
  int (*A2d)[4] = new int[n][4]; // The auto type resolved 
Ah, thank-you for the explanation, @coder777.

Topic archived. No new replies allowed.