I was trying to create 2D array in a continuous memory block, but it is giving M continuous block, each of N size.
int **arr = new int*[M];
for (int i = 0 ; i < M ; i++ )
{
arr[i] = new int[N];
}
How to create 2D array in a continuous memory block?
A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.
The right syntax for a dynamic array is int* arr = new int[5]; . Yes, it will be allocated contiguously.
The data items in a multidimensional array are stored in the form of rows and columns. Also, the memory allocated for the multidimensional array is contiguous.
Question: How two dimensional array is stroed in memory? Answer: Let a be a two dimensional m x n array. Though a is pictured as a rectangular pattern with m rows and n columns, it is represented in memory by a block of m*n sequential memory locations.
int *buffer=new int[M*N];
int **arr=new int*[M];
for(int i=0;i<M;++i)
arr[i]=buffer+i*N;
Actually it's not necessary to store arr pointers - they can be calculated when needed.
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