Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating two-dimensional array dynamically in continuous memory block

Tags:

c++

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?

like image 936
Nawaz Avatar asked Dec 29 '10 06:12

Nawaz


People also ask

Can we allocate a 2 dimensional array dynamically?

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.

Are dynamic arrays contiguous in memory?

The right syntax for a dynamic array is int* arr = new int[5]; . Yes, it will be allocated contiguously.

Is 2D array contiguous?

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.

How a two-dimensional array can be implemented in memory?

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.


1 Answers

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.

like image 68
maxim1000 Avatar answered Sep 30 '22 12:09

maxim1000