when we create 2D dynamic array in c++ we crate a double pointer which by definition stores the address of a pointer pointing to the first element of n rows array, but it actually directly holds the address of the first element and not the address of the pointer pointing to that element as it should. Like int**ptr=new int*[], ptr[i] holds the address of the first element of ith row and not the address of the pointer. What am I missing? Where am I going wrong? But while doing the same implementation in stack memory for example this code:
#include
using namespace std;
int main(){
int ptr0[4]={1,2,3,4};
int ptr1[4]={5,6,7,8};
int ptr2[4]={9,10,11,12};
int *ptr[3];
ptr[0]=ptr0;
ptr[1]=ptr1;
ptr[2]=ptr2;
int i,j;
cin>>i>>j;
cout<<ptr[i][j];
return 0;
} in this, we created a pointer array to hold the address the 3 arrays and not a double pointer.
I thought I could use single pointer array to hold the address of 1st element of i’th row but we actually use double pointer array which holds new int[], which is nothing but address of the first element of i’th array.
Ayush Mishra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.