+ 6
What is the difference between int **p1 and int *p2 ?
5 Answers
+ 3
can you write some code and tell me how to use p1 to store 1d pointer arrays as elements inside an array
+ 2
@chris
You may run this code:
#include<iostream>
using namespace std;
int main()
{
int size=5;
int* p = new int[5]{1,2,3,4,5};
// Pointer array to be stored in p1.
int** p1 = new int*[5];
for(int i=0;i<5;i++)
{ p1[i] = p+i; }
for(int i=0;i<5;i++)
{
for(int j=0;j<size;j++)
{ cout<<p1[i][j]<<" "; } size--;
cout<<endl;
}
}
/*
Output :
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
*/
+ 2
@chris
No. int* a[] is a 2D array as opposed to a simple 1D array, though it looks like a 1D array. This is as it is a declaration of an array of int* s.
But you are not allowed in c++ to declare arrays without a number inside the [], but you can use these in type casting. (May result in pedagogical errors/warnings though).
Similarly, int** p1[][] would be, if valid, a 4D array instead of a 2D array.
+ 1
p1 is a pointer to a pointer, AKA a dynamic 2D array. You may use p1 to store the address of a pointer or store 1D pointer arrays as elements inside an array (array of arrays).
p2 is a simple pointer, or a dynamic 1D array. You nay use p2 to store the address of a static variable or store collection of variables inside contiguous memory addresses in the dynamic memory pool.
0
Do you come across input anomalies often when developing playground scenarios and then receiving illogical responses?