2d pointers in c++ code example
Example 1: c++ 2D vectors
int main()
{
int row = 5;
int colom[] = { 5, 3, 4, 2, 1 };
vector<vector<int> > vec(row);
for (int i = 0; i < row; i++) {
int col;
col = colom[i];
vec[i] = vector<int>(col);
for (int j = 0; j < col; j++)
vec[i][j] = j + 1;
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < vec[i].size(); j++)
cout << vec[i][j] << " ";
cout << endl;
}
}
Example 2: accessing elements 2D array using pointers
#include<stdio.h>
int main(void){
int arr[4][4]={{1,2,3,4},{5,6,7,8},{9,0,1,2}};
int *ptr = &arr;
for(int i=0;i<3;i++){
for(int j=0;j<4;j++)
printf("%d ",*((ptr+i*4)+j));
printf("\n");
}
return 0;
}