+ 4

Challenge: Index an element of an n-dimensional array using pointers arithmetic.

You can not use moltiplication!!! For example: int matrix[20][20]; matrix[10][5] = 30; //Now print matrix[10][5] using pointers arithmetic cout << *((int*)matrix+(10*20)+5) << endl; cout << *((int*)matrix+(200)+5) << endl; //Both are not valid for this challenge (10*20 is a moltiplication) //Then try with a 3-dimensional array, always without moltiplications int t[10][15][20]; t[8][12][16] = 30; //Now print t[8][12][16] using pointers arithmetic.

15th Jun 2017, 9:34 AM
Andrea Simone Costa
Andrea Simone Costa - avatar
10 Réponses
+ 3
moltiplication is a repeated addition...so no you cant...you need another tipe of addition ;)
15th Jun 2017, 10:41 AM
Andrea Simone Costa
Andrea Simone Costa - avatar
+ 2
Can we use repeated addition? 😅 I don't think so...
15th Jun 2017, 10:37 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
No i am sorry. If you create a matrix using pointers-to-pointers you are right. But try with a normal matrix (int matrix[20][20]) and a normal 3d array (int t[10][15][20])
15th Jun 2017, 10:57 AM
Andrea Simone Costa
Andrea Simone Costa - avatar
+ 2
XD now in 3d
15th Jun 2017, 11:13 AM
Andrea Simone Costa
Andrea Simone Costa - avatar
+ 2
Sure: #include<iostream> using namespace std; int main() { int mat[9][9][9]; mat[4][7][1]=30; mat[1][2][3]=33; cout<<*(*(*(mat+1)+2)+3); //Format - *(*(*(mat+slice)+row)+column) }
15th Jun 2017, 11:20 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
Good.
15th Jun 2017, 11:22 AM
Andrea Simone Costa
Andrea Simone Costa - avatar
+ 2
Last question: mat is not a *** but a (*)[9][9] so why triple dereferentiation work? 😂😂😂 How the compiler consider it? What does it really do?
15th Jun 2017, 11:25 AM
Andrea Simone Costa
Andrea Simone Costa - avatar
+ 2
The operator[] is overloaded in the following way, thats why... T being a custom type... T operator[](int index) { return *(arr+index); } Now, C++ has defined these operators and created arrays etc from pointers. So they are simply the same thing. But int*** a is != int*[9][9], as the second one has a fixed number of elements, but the *** one is resizable...
15th Jun 2017, 3:15 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
I win! #include<iostream> using namespace std; int main() { int** mat=new int*[9]; for(int i=0;i<9;i++) mat[i]=new int[9]; mat[4][7]=30; mat[7][4]=33; cout<<*(*(mat+7)+4); //Format - *(*(mat+row)+column); }
15th Jun 2017, 10:55 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
@Andrea Is this ok? :) #include<iostream> using namespace std; int main() { int mat[9][9]; mat[4][7]=30; mat[7][4]=33; cout<<*(*(mat+4)+7); }
15th Jun 2017, 11:09 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar