C++ Multi-dimensional Array Comma Index Address -


in playing around multi-dimensional arrays, found if used comma separate indices, return me address of element in array, disregarding first comma. shown following example:

int arr[3][3];  (int = 0; < 3; i++) {     (int j = 0; j < 3; j++) {         // output arr[,] test         cout << "arr[" << << "," << j << "]: " << arr[i,j] << endl;     } } cout << "\n--------------\n" << endl; (int = 0; < 3; i++) {     (int j = 0; j < 3; j++) {         // output arr[][] test         cout << "arr[" << << "][" << j << "]: " << &arr[i][j] << endl;     } } 

this gives output:

arr[0,0]: 0x28feec arr[0,1]: 0x28fef8 arr[0,2]: 0x28ff04 arr[1,0]: 0x28feec arr[1,1]: 0x28fef8 arr[1,2]: 0x28ff04 arr[2,0]: 0x28feec arr[2,1]: 0x28fef8 arr[2,2]: 0x28ff04  --------------  arr[0][0]: 0x28feec arr[0][1]: 0x28fef0 arr[0][2]: 0x28fef4 arr[1][0]: 0x28fef8 arr[1][1]: 0x28fefc arr[1][2]: 0x28ff00 arr[2][0]: 0x28ff04 arr[2][1]: 0x28ff08 arr[2][2]: 0x28ff0c 

as can see, address values @ [0,0]/[0][0], [0,1]/[1][0], , [0,2]/[2][0] match up. match wherever second 1 in [n,n] pair matches first number in [n][n] pair.

i found wikipedia article comma operators in c++ agrees skipping:

in pascal, multidimensional arrays indexed using commas, e.g. a[i, j]. in c, however, a[i, j] equivalent a[j], since value of i discarded. correct way index multidimensional arrays in c construction a[i][j].

the question have is: why return address? have tried find reason behind this, utterly stumped. wikipedia article seems disagree should return address, because says "equivalent a[j]". appreciate answer this. ahead of time!

when addressing multi-dimensional array, indices separated comma arr[i,j] , comma behaves comma operator.

a comma operator binary operator evaluates comma separated expressions completing side effects , discards until last expression in list. effectively, ignored indices sans last 1 in particular case j arr[j].

as type of arr[j] nothing more int arr[3], decays pointer int *, printing value of pointer displays address.


to expand on this, ostream operator not have overload can accept type ty[], closest accepts ty*,

ostream& operator<< (void* val);  

so means, ty[] decays ty* downcasted void * , calls ostream& operator<< (void* val), prints address of pointer


the wikipedia article seems disagree should return address, because says "equivalent a[j]". appreciate answer this.

to make simple, expect program print in following case?

int arr[3]; std::cout << arr << std::endl; 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -