Below is the code
void printLoop(type?? p){
for(int i = 0; i<2;i++)
{
for(int e = 0;e<3;e++)
{
cout<<p[i][e]<<" ";
}
cout<<"\n";
}
}
void array()
{
int a[2][3] = {{1,2,3},{4,5,6}};
int (*p)[3] = a;
printLoop(p);
}
Basic idea is that I want to print out the array using a for loop in the printLoop func. However, I need to know the type of that pointer which has the address of the 2D array. What’s the pointer’s type? Is it int (*)[]? I’m confused.
Also what does “(*p)” mean(from int (*p)[3]) ? Thanks a lot!
pis a pointer to an array of size3of objects of typeint.You have multiple possibilites for your
printLoopfunction (though with the general C-restriction that you can leave at most one — the outermost declarator empty):You can specify the dimensions explicitly:
void printLoop(int p[ 2 ][ 3 ]);The only advantage with this method is that the implementation can consider that the array being passed is of the desired size (i.e. 2×3 matrix of
ints) as a pre-condition.You can leave out the [ 2 ] part entirely:
void printLoop(int p[][ 3 ]);or,
intYou will also need to pass the dimensions (if you skip one that is) along to make sure that you don’t access out-of-bounds memory. So, your function signature should go like this: