views:

200

answers:

5

I want to know what is happening in memory when you declare:

int **array;
+8  A: 

It creates a variable to store a pointer to an int pointer.

Idan K
+2  A: 

It's a pointer to an int pointer. This is often used to declare a 2D array, in which case each int pointer is an array and the double pointer is an array of arrays.

Sean
+4  A: 

You're declaring a pointer variable, so you're allocating enough space for one memory address (depends on your platform/compiler/etc.)

The type system will ensure that the only addresses you assign into it contain other memory addresses, and that these addresses represent the actual address of an integer variable.

To use your pointer-to-pointer, you dereference it once (to get the address that actually points to the integer), and then a second time (to get the actual integer).

You can bypass the type system by explicitly casting to something else (e.g., i=&pDouble) but that is not recommended unless you're sure you know what you're doing.

If you have a two-dimensional array, you can think of it conceptually as one single-dimensional array of single-dimensional arrays representing rows. The first level of indirection would be to pick the row, and the other one to pick the cell in the row.

Uri
+6  A: 

The compiler reserves four bytes (on a 32bit system, eight bytes on 64bit) to store a pointer (that would point to another pointer, that would point to an int). No further memory allocation is done, it is left to the programmer to actually set the pointer to point to some other memory location where the int*/array/... is stored.

sth
A: 

If I am not mistaken...

You have a multidimensional array arr[i][j] and

**arr addresses to arr[0][0]

*((*arr)+1) addresses to arr[0][1]

*(*(arr+1)+1) addresses to arr[1][1]

Sample code in C++

#include <iostream>

using namespace std;

int main()
{
int **arr;

arr = new int*[5];

for(int i = 0; i < 5; i++)
    arr[i] = new int[5];

arr[0][1] = 1;

cout << *((*arr)+1); // prints 1
cout << arr[0][1] = 1; // prints 1

}
JCasso
This is technically correct but doesn't answer the original question.
Graeme Perrow
Actually I am new to this place. What happens on memory is pointed by sth. I gave extra information which is not out of topic. Saying **ar ADDRESSES to arr[0][0] OBVIOUSLY means "you only declare a pointer, just like *p" Is that out of format? I do ask because I really wonder that.
JCasso
Up-voted because the answer is correct. Just because it isn't *exactly* what the questioner wanted doesn't make it worthy of dismissal.
Daniel Spiewak