Answers for "2d pointers in c++"

C++
0

accessing elements 2D array using pointers

#include<stdio.h>
//accessing elements of 2D array using pointers
int main(void){

    int arr[4][4]={{1,2,3,4},{5,6,7,8},{9,0,1,2}};
    int *ptr = &arr;

    //accessing the elements of 2D array using ptr
    for(int i=0;i<3;i++){
            for(int j=0;j<4;j++)
            printf("%d ",*((ptr+i*4)+j)); //4 is the number of columns
            //*((ptr+i*4)+j) is similar to arr[i][j]
            printf("n");
    }
    return 0;
}
Posted by: Guest on June-18-2020
1

c++ 2D vectors

int main() 
{ 
    int row = 5; // size of row 
    int colom[] = { 5, 3, 4, 2, 1 }; 
  
    vector<vector<int> > vec(row);  // Create a vector of vector with size equal to row. 
  	for (int i = 0; i < row; i++) { 
  		int col;  
        col = colom[i]; 
  		vec[i] = vector<int>(col); //Assigning the coloumn size of vector
        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; 
    } 
}
Posted by: Guest on July-27-2020

Browse Popular Code Answers by Language