2

I've bought a beginners book for visual c++ and have come the chapter which involves arrays, strings and pointers. I understand the concept, but when it comes to multidimensional arrays I got a bit lost.

Array and and pointer declaration:

double beans[3][4];
double* pbeans;

I understood this part:

*You can declare and assign a value to the pointer pbeans, as follows:

double* pbeans;
pbeans = &beans[0][0];

But when the author presents that you can assign the address for the first row/dimension by typing this statement he lost me:

pbeans = beans[0];

Why can we skip the "Address-Of" operator here? To me the logical thing would be:

pbeans = &beans[0];
Mogash
  • 130
  • 1
  • 7
  • 2
    [This FAQ](http://stackoverflow.com/q/4810664/1202636) is really useful if you're fighting with arrays, pointers and theri relationships. – effeffe Dec 10 '12 at 23:00
  • 1
    Check out http://stackoverflow.com/questions/2565039/how-are-multi-dimensional-arrays-formatted-in-memory – devshorts Dec 10 '12 at 23:01

3 Answers3

0

Say you have just an array

double legumes[5];

Arrays decay to pointers so you can do

double* plegumes = legumes;

When you declare a 2d array, what you're doing is creating an array of arrays. So the expression beans[0] actually refers to an array. So the statement

pbeans = beans[0];

Is just assigning an array to a pointer.

David Brown
  • 13,336
  • 4
  • 38
  • 55
0

Because an array decays to a pointer to the first element. If we have an array called arr, then any usage of arr where an array won't fit will generally result in arr being treated as a pointer. This is called decay.

In this case, beans[0] is an array; to be specific, an double[4]. However, as you cannot assign an array to a pointer, the array decays into a double*.

The code you provided, double* pbeans = &beans[0]; would be trying to assign a pointer to an array of doubles to a pointer to a double; that won't work due to a type mismatch.

Also, all that aside, this doesn't sound like a very good book; teaching arrays, strings and pointers together smells of C.

Cactus Golov
  • 3,474
  • 1
  • 21
  • 41
0

There is a standard conversion between array types and pointers to the first element of the array. As a simpler example:

int array[5];
int* p = array;

p is now a pointer to the first element of array, because objects of type "array of 5 int" will decay to a "pointer to int" if they need to.

In your case, beans[0] is of type "array of 4 double" and will decay into a "pointer to double" that points at the first element in the beans[0] array. It is equivalent to doing double* p = &beans[0][0].

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324