eChung00
eChung00

Reputation: 631

Declaring an array of pointers in C++

When I make an array of integer pointers, I tried this.

int *arr = new int*[10];

This did not work but the following worked.

int **arr = new int*[10];

Why do we need double pointer?? And when I deference it, I had to do the following.

cout<<arr[0];

Why we do not need * in front of arr?? thanks!

Upvotes: 1

Views: 397

Answers (3)

dspfnder
dspfnder

Reputation: 1123

This statement is an expression for an 1D array of int

int* arr = new int [10]; // pointer to array of 10 int

This statement is an expression for a 2D array of int

int** arr = new int* [10]; // pointer to 10 pointers to arrays of 10 int

To populate the 1D array, you need to do this...

for (int i = 0; i < 10; i++) {
        arr[i] = val; // where val can be any integer
}

To populate the 2D array, you need to do this...

int** arr2 = new int*[10];
for (int i = 0; i < 10; i++) {
    arr2[i] = new int[10];
    for (int j = 0; j < 10; j++) {
        arr2[i][j] = val; // where val can be any integer
    }
}

The * symbol between the variable type and the variable name is syntax for pointer. It changes type from int to pointer of int.

Upvotes: 0

Columbo
Columbo

Reputation: 61009

new int*[10] allocates an array of ten pointers, and it yields a pointer to the first element of that array. The element type is itself a pointer, that's why you end up having a pointer to a pointer (to int), which is int**. And obviously int** isn't convertible to int*, so you have to declare arr with the appropriate type.

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

You are not just "making an array of integer pointers": you are dynamically allocating them.

Just like when you dynamically allocate an array of integers you get a single pointer through which to access them:

int* ptr = new int[5];

when you dynamically allocate an array of pointers-to-integer you get a single pointer through which to access those, too; since your element type is int*, adding the extra * gives you int**:

int** ptr = new int*[5];

As for dereferencing, I'm not quite sure what you're asking but that's just how the [] operator works; it adds n to a pointer then dereferences it:

int* ptr = new int[5];
*(ptr+1) = 42;         // identical
  ptr[1] = 42;         // to this

If you forget dynamic allocation and just make a nice array, it's all much simpler:

int* array[5];
std::cout << array[0];

Upvotes: 1

Related Questions