Reputation: 2805
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!
Upvotes: 1
Views: 109
Reputation: 5101
First of all, your code is not very modern C++. It's basically "c with iostreams".
Second of all, printLoop(int p[2][3])
is the signature you're looking for even though again, it's not the best way of doing things at all.
Third of all, int (*p)[3]
is analyzed as follows: Start at the name which is p
and take a look around (first to the right and then to the left yet here it doesn't matter) until you "hit" braces. There's only a star at it, so you can say that p is a pointer. Now you recursively do the same analysis again, you see [3]
, which means that p
is a pointer to an array that has 3 int
s.
Now I'd like to mention the following:
Use std::array
for staticly-sized arrays.
Use std::vector
for dynamicaly-sized arrays.
Oh, also, I myself wouldn't use a 2D array, they are clunky and just a syntactic sugar (around the basic "array" notion which is a syntactic sugar as well).
So perhaps, something like this, brain compiled, hopefully correct, C++11 abusing:
std::array<int, 3 * 2> p = {{1, 2, 3, 4, 5, 6}};
std::for_each(std::begin(p), std::end(p), [](int elem){ std::cout<<elem; });
Nice and dandy. You could also have lambda check for some "2d array" sizes and insert newlines if you so desire.
Upvotes: 2
Reputation: 111130
what does "(*p)" mean(from int (*p)[3]) ?
p
is a pointer to an array of size 3
of objects of type int
.
You have multiple possibilites for your printLoop
function (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. 2x3 matrix of int
s) as a pre-condition.
You can leave out the [ 2 ] part entirely:
void printLoop(int p[][ 3 ]);
or,
void printLoop(int (*p)[ 3 ]);
int
You 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:
void printLoop(int (*p)[ 3 ], int dim);
Upvotes: 4
Reputation: 81349
For the printLoop
function, int p[2][3]
as an argument should just work.
int (*p)[3] = a;
p
is a pointer to an array of 3 int
s, initialized to point to a
.
Upvotes: 3