Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int ** vs int [ROWS][COLS] [duplicate]

Tags:

c++

c

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])?

like image 255
PKG Avatar asked Jun 01 '10 16:06

PKG


3 Answers

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.

like image 171
jweyrich Avatar answered Nov 19 '22 20:11

jweyrich


You are attempting to assign a double pointer variable to an array... this has been covered exhaustively, see here for information on this. Furthermore, since you declared

int arr[2][2] = ...;

and then try to assign arr to a double pointer

int ** ptr = ... ;

which is guaranteed to not work, hence a segmentation fault. Furthermore, that statement int ** ptr=(int**) arr; is actually cast ing one type (i.e. [][]) to another type (i.e. **) despite they are of type 'int'. They are both different and the compiler will interpret that very differently...

You could do it this way:

int *ptr = &arr;

Now *(ptr + 1) will refer to the 0'th row, *(ptr + 2) will refer to the 1'st row and so on. The only onus on you is to not overstep the markers of where arr is used otherwise an overflow can happen or even a segmentation fault...

like image 24
t0mm13b Avatar answered Nov 19 '22 22:11

t0mm13b


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.

like image 2
M. Williams Avatar answered Nov 19 '22 22:11

M. Williams