tags:

views:

180

answers:

6

Possible Duplicate:
casting char[][] to char** causes segfault?

I have a 2D array declared like this:

int arr[2][2]={ {1,2},{3,4}};

Now if I do:

int ** ptr=(int**) arr;

and:

cout<<**ptr;

I am getting a segmentation fault (using g++-4.0).

Why so? Shouldn't it be printing the value 1 (equal to arr[0][0])?

A: 

Try

int *ptr = arr;

More Explanation:

You should assign an adress to the pointer, so it can be derefenced(i mean * operator). What you do is, pointing ptr to memory cell that has the adress a[0][0]. Therefore, you get a segmentation fault.

Ayberk
+5  A: 

You can't cast a linear array to a pointer-to-pointer type, since int** doesn't hold the same data int[][] does. The first holds pointers-to-pointers-to-ints. The second holds a sequence of ints, in linear memory.

jweyrich
Well, you "can", as the OP demonstrates. You just have to do a reinterpret_cast, which the OP unknowingly did because they're using c-style casts. As with all such casts of course the result of accessing the new pointer is UB. The moral the OP should be getting is: use C++ casts in C++.
Noah Roberts
+1  A: 

No, int ** is a pointer to a pointer to an int, but a 2-D array is an array of arrays, and &(arr[0][0]) is a pointer to an int.

I believe you should be doing this:

int *ptr = arr;
cout<<*ptr; 

or this:

int *ptr = &arr[0][0];
cout<<*ptr; 
Cade Roux
+2  A: 

What you do now means creating of arrays of pointers where every pointer was explicitly casted. Therefore, you would have an array of pointers like (0x00001, 0x00002, 0x00003 and 0x00004).

When dereferenced, this pointers cause your segfault.

Kotti
+1  A: 
tommieb75
A: 

int arr[2][2] is not an array of arrays - it is a single 2d array. In memory, it is indistinguishable from int arr[4]

What you really want is

int (*ptr)[2] = arr;
BlueRaja - Danny Pflughoeft
Formally, it *is* an array of arrays. But yes, since arrays are laid out contiguously with no padding allowed, an `int [2][2]` is indeed laid out exactly like an `int [4]` in memory.
caf