Declaring and allocating a 2d array in C++

前端 未结 5 1816
天命终不由人
天命终不由人 2021-01-21 18:01

I am a Fortran user and do not know C++ well enough. I need to make some additions into an existing C++ code. I need to create a 2d matrix (say A) of type double whose size (say

5条回答
  •  -上瘾入骨i
    2021-01-21 18:26

    To allocate dynamically a construction similar to 2D array use the following template.

    #include 
    
    int main()
    {
       int m, n;
    
       std::cout << "Enter the number of rows: ";
       std::cin >> m;
    
       std::cout << "Enter the number of columns: ";
       std::cin >> n;
    
       double **a = new double * [m];
    
       for ( int i = 0; i < m; i++ ) a[i] = new double[n]();
    
       //...
    
       for ( int i = 0; i < m; i++ ) delete []a[i];
       delete []a;
    }
    

    Also you can use class std::vector instead of the manually allocated pointers.

    #include 
    #include 
    
    int main()
    {
       int m, n;
    
       std::cout << "Enter the number of rows: ";
       std::cin >> m;
    
       std::cout << "Enter the number of columns: ";
       std::cin >> n;
    
       std::vector> v( m, std::vector( n ) );
    
       //...
    
    }
    

    As for this code snippet

    int * x;
    x = new int [10];
    

    then x has type int * and x[0] has type int. So if the size of the pointer is equal to 4 and the size of an object of type int is equal also to 4 then sizeof( x ) / sizeof( x[0] ) will yields 1. Pointers do not keep the information whether they point to only a single object or the first object pf some sequence of objects.

提交回复
热议问题