3

I am confused by the slides in my c++ course. On the one hand in Example 1 int(*foo)[5] is a pointer to an integer array of 5 elements, but in Example 2 int(*numbers2)[4] points to an array of arrays (4 arrays) of type integer. How can these two have the same lefthand declaration but hold different types?

#include <iostream>
using std::cout;
using std::endl;


int main() {

    //Example1
    int numbers[5] = { 1,2,3,4,5 };
    int(*foo)[5] = &numbers;
    int *foo1 = *foo;


    //Example2 
    int numRows = 3;
    int(*numbers2)[4] = new int[numRows][4];
    delete[] numbers2;


    return 0;

}
IntegrateThis
  • 853
  • 2
  • 16
  • 39
  • 1
    `numbers2` points to the *first element* of the dynamic array. That's now `new` expressions work. – Kerrek SB Oct 02 '16 at 17:46
  • 2
    Think a little... If you allocate a plain array of integers then `new int[numRows]` return `int*`. So when you allocate an array of array you get a pointer to an array, or `int (*)[4]` (in your specific case). – Some programmer dude Oct 02 '16 at 17:47
  • 2
    An `int*` can point to a single integer or to the address of the first element of an array of integers. Same is true of a pointer to an array. It can point to a single array or the address of the first element of an array of arrays. – Galik Oct 02 '16 at 17:51

2 Answers2

3

Check pointer declaration reference:

Because of the array-to-pointer implicit conversion, pointer to the first element of an array can be initialized with an expression of array type:

int a[2];
int* p1 = a; // pointer to the first element a[0] (an int) of the array a

int b[6][3][8];
int (*p2)[3][8] = b; // pointer to the first element b[0] of the array b,
                     // which is an array of 3 arrays of 8 ints

So essentially speaking what lefthand numbers2 and foo point to on the right hand side matters.

So in following numbers2 point to first element of temporary (yet unnamed) array which is an array of numRows arrays of 4 ints

 int(*numbers2)[4] = new int[numRows][4];

While foo points to first element of numbers which is an array of 5 ints

int(*foo)[5] = &numbers;
Community
  • 1
  • 1
JamesWebbTelescopeAlien
  • 3,547
  • 2
  • 30
  • 51
2

The description in your question of example 2 is not exactly correct.

Try phrasing like this and you will see the parallelism.

  • foo is a pointer to the first object, each object is an integer array of 5 elements. (As it turns out, the first one is the only one)
  • numbers2 is a pointer to the first object, each object is an integer array of 4 elements. (As it turns out, there are a total of numRows of them)

A pointer data type doesn't tell you the number of objects it points to, only the type of each one.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720