-1

In ReadVector() why do I have to write int a[][20]? What is the purpose of [20]. Why can't I write a[][]?

int a[20][20 ], n,m;

int ReadVector(int a[][20],int n,int m){
for (int i=0; i<n; i++)
        for (int j=0; j<m; j++){
            cout<<"a["<<i<<","<<j<<"]=";
            cin>>a[i][j];
            }

 return *a[20];`
A. Sarid
  • 3,716
  • 2
  • 23
  • 48
L.Robert
  • 21
  • 3

2 Answers2

2

When you acces rows via a[i] the second dimension has to be know, to get to the right memory address, because

&(a[i]) = &(a[0]) + i*m*sizeof(int)

So when you acces an element, the offsets are calculated via:

&(a[i][j]) = &(a[0]) + i*m*sizeof(int) + j

Just consider how you would find an element at position [i][j] in a matrix if you were only allowed to count the elements starting from the first one...to make this work you have to know at least how many elements are there in a row.

463035818_is_not_a_number
  • 64,173
  • 8
  • 58
  • 126
-1

Why can't I write a[][]?

Because int a[][] is the same as int **a (a pointer to a pointer to char) which is not the same as int a[][20] which is the same as int (*a)[20] (a pointer to a char[20]).

Applying the same pointer arithmetic to int **a results in something different then it will for int (*a)[20].

alk
  • 66,653
  • 10
  • 83
  • 219