+ 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.
10 Answers
+ 3
moltiplication is a repeated addition...so no you cant...you need another tipe of addition ;)
+ 2
Can we use repeated addition? đ
I don't think so...
+ 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])
+ 2
XD
now in 3d
+ 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)
}
+ 2
Good.
+ 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?
+ 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...
+ 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);
}
+ 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);
}