A pointer to an array: int* p=arr; vs. int (*p2)[10] = &arr; ?

Hello,

1
2
3
int arr[10];
int* p = arr;
int (*p2)[10] = &arr;


So, pointer p is a pointer to an array, I can use it to access elements of arr as in *(p+5).

Pointer p2 is a pointer to an array of ten integers. What is it for, how can I use it to access elements of arr?

Thank you.
vincegata wrote:
So, pointer p is a pointer to an array
No, p is a pointer to the first int in an array, which is very different from being a pointer to an array like p2.
vincegata wrote:
Pointer p2 is a pointer to an array of ten integers. What is it for, how can I use it to access elements of arr?
1
2
(*p2)[index] = blah;
std::cout << (*p2)[index] << std::endl;
Last edited on
Also,

p2 is in fact a pointer to an array of an array of ints, so p2 is used to deal with 2D arrays. Alternatively I can access its elements:

 
std::cout << p2[0][0] << std::endl;


Thank you.
@vincegata

I would like to know how you can tell from "Type *p" whether it is a pointer to one object or an array of objects.

1
2
Type *p1 = new Type;
Type *p2 = new Type[10];
I see no difference between "p1" and "p2" - you would have to look at how they are initialized to know.

This is why sue of pointers is generally discouraged and use of automatic pointers and container classes is recommended instead.
I do not have initialization, I saw the syntax for p2 and I wanted to know what is it for.

Thx for clarification.
vincegata wrote:
I do not have initialization
vincegata wrote:
int (*p2)[10] = &arr;
You have contradicted yourself.

If you do not have initialization then it is near-impossible to know how it is meant to be used.
I do not have a "proper" initialization. I only saw the syntax for p2 and I wanted to know what is it for.
I know, I'm just pointing out to you that you cannot determine how to use a variable solely from its syntax.
Neither of those explains whether the pointer to the array can be incremented to access a different array.
Topic archived. No new replies allowed.