1

I am trying the following code for multi-dimensional array. It gives SEG error I do not know what is the issue in this.

 static void read(double **arr){
  //REQ arr to be pointing to  array[5][4] 
  //EFF prompt the use to input the data
  //Mod array pointer by **arr
       int i(0) , j(0);
       double tmp ;


       for(i=0 ; i<4 ; i++){

            for(j=0 ; j<5 ; j++) {
                cout <<"Please enter Data#"<<  (j+1) << " File#" << (i+1)  <<" "<<flush;

                cin >> tmp ; 
                arr[j][i] = tmp ;
            }   

        }

        return ; 
    }


int main(){
 double arr[5][4] ;
 read(reinterpret_cast<double**>(arr) ) ;
}

What am i doing wrong here?

Useless
  • 64,155
  • 6
  • 88
  • 132
  • Is there any reinterpret_cast in C? –  Dec 18 '13 at 11:39
  • @NishithJainMR This isn't C. I don't know why he used that tag. – David G Dec 18 '13 at 11:40
  • Arrays in C++ are not implemented as pointers to pointers. It is implemented as a contiguous section of memory. So `arr[2][3]` Is more likely to be equivalent to `arr + 2*(sizeof(int)*4) + 3*sizeof(int)` – Martin York Dec 18 '13 at 11:40

2 Answers2

5

You are using 2D array which is stored the same way as linear arrays (the dimensions are used for indexing only), however you are interpreting is as an pointer to (array of) pointer(s) to (array of) double(s), which has completely different memory layout. See this and this SO question.

Community
  • 1
  • 1
Erbureth
  • 3,378
  • 22
  • 39
3

An array of arrays is not the same as a pointer to pointer.

Lets look at how they are laid out in memory:

Array of arrays:

+-----------+-----------+-----+-----------+-----------+-----+-----------+
| arr[0][0] | arr[0][1] | ... | arr[0][3] | arr[1][0] | ... | arr[4][3] |
+-----------+-----------+-----+-----------+-----------+-----+-----------+

Compare to pointer-to-pointer (e.g. double** arr):

+-----+      +--------+--------+-----+
| arr | ---> | arr[0] | arr[1] | ... |
+-----+      +--------+--------+-----+
                 |        |
                 |        `------.
                 |               |
                 v               v
             +-----------+   +-----------+
             | arr[0][0] |   | arr[0][1] |
             +-----------+   +-----------+

The solution is to change your function so it either takes an array of arrays:

void read(double arr[][4]) { ... }

Or a pointer to an array (this works because arrays decays to pointers):

void read(double (*arr)[]) { ... }

Then you can pass the array without casting:

double arr[5][4];
read(arr);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • void read(double (*arr)[]) { ... } I have tried it but I have compilation error . It doesn't work Thank you for your help – user2990971 Dec 19 '13 at 03:36