Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

c++ - difference between pointer to an array and pointer to the first element of an array

int (*arr)[5] means arr is a pointer-to-an-array of 5 integers. Now what exactly is this pointer?

Is it the same if I declare int arr[5] where arr is the pointer to the first element?

Is arr from both example are same? If not, then what exactly is a pointer-to-an-array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Theory

First off some theory (you can skip to the "Answers" section but I suggest you to read this as well):

int arr[5]

this is an array and "arr" is not the pointer to the first element of the array. Under specific circumstances (i.e. passing them as lvalues to a function) they decay into pointers: you lose the ability of calling sizeof on them.

Under normal circumstances an array is an array and a pointer is a pointer and they're two totally different things.

When dealing with a decayed pointer and the pointer to the array you wrote, they behave exactly the same but there's a caveat: an array of type T can decay into a pointer of type T, but only once (or one level-deep). The newly created decayed type cannot further decay into anything else.

This means that a bidimensional array like

int array1[2][2] = {{0, 1}, {2, 3}};

can't be passed to

void function1(int **a);

because it would imply a two-levels decaying and that's not allowed (you lose how elements of the array are laid out). The followings would instead work:

void function1(int a[][2]);
void function1(int a[2][2]);

In the case of a 1-dimensional array passed as lvalue to a function you can have it decayed into a simple pointer and in that case you can use it as you would with any other pointer.


Answers

Answering your questions:

int (*arr)[5]

this is a pointer to an array and you can think of the "being an array of 5 integers" as being its type, i.e. you can't use it to point to an array of 3 integers.

int arr[5]

this is an array and will always behave as an array except when you pass it as an lvalue

int* ptrToArr = arr;

in that case the array decays (with all the exceptions above I cited) and you get a pointer and you can use it as you want.

And: no, they're not equal otherwise something like this would be allowed

int (*arr)[5]
int* ptrToArr = arr; // NOT ALLOWED

Error cannot convert ‘int (*)[5]’ to ‘int*’ in initialization

they're both pointers but the difference is in their type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...