Then how is the following code possible: |
What's going on when you assign a one dimensional array to a pointer of the same time, and also when you pass one to a function which takes a pointer of the same type, is referred to as
array decay.
what is array decaying?
http://stackoverflow.com/questions/1461432/what-is-array-decaying
Notes
- The decay mechanism only works with the first index.
- when used in a function declaration, [] means pointer! e.g.
void message(char text[]);
This is apparently hang over from BCPL, the language that C was derived from.
(This bit of random knowledge comes from this article by Dennis Ritchie:
The Development of the C Language
http://people.fas.harvard.edu/~lib113/reference/c/c_history.html
I found while hunting for the reason that * binds to the right, i.e. why writing
int* a = 0, b = 0;
is dangerous.)
You could hack a little bit and cast the 2D-array with a reinterpret_cast to int*. |
You don't have to be quite so brutal: either use a single [0] to get a row and rely on it to decay to a pointer, or two [0]'s to acquire the first element and take its address. No coercion required.
int* p2 = arr2[0];
int* p2 = &arr2[0][0];
Andy
PS When you wrote
int* nobody = new int(420);
you did realise you were new-ing a single int with value of 420 rather than an array of 420 ints? (Just checking as the following discussion has been about arrays?)