C++ using arrays as multidimensional despite initalising it as 1D with pointer

  • A+
Category:Languages

apperently this code works.

int main() { const int size = 5; int *triangle[size], i, j;  for (i = 0; i < size; i++){     triangle[i] = new int[i + 1];     for (j = 0; j < i + 1; j++)         triangle[i][j] = i + 1; } for (i = 0; i < size; i++){     for (j = 0; j < i + 1; j++)         cout << triangle[i][j];     cout << endl; } for (i = 0; i < size; i++)     delete [] triangle[i];  return 0; } 

It gives it output 1 22 333 4444 55555

But isn't writing int*triangle[ size] shows that is a 1D array, we dont specify anything about the second parameter. But then we use at it is like a 2D array by writing triangle[i][j] = i + 1;I dont understand where that j(second parameter) come from. Shouldn't it give a compile error or something?

 


int *triangle[size] is an array of pointers. In your for loop you do

triangle[i] = new int[i + 1] 

which sets each pointer to point to an array. We put that together and

triangle[i][2]          +  +          |  +> access the element of the array the ith pointer points to          |          +-> Accesses the ith pointer 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: