Declaring and allocating a 2d array in C++

前端 未结 5 1814
天命终不由人
天命终不由人 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条回答
  •  再見小時候
    2021-01-21 18:33

    int ** x;
    x = new int* [10];
    for(int i = 0; i < 10; i++)
        x[i] = new int[5];
    

    Unfortunately you'll have to store the size of matrix somewhere else. C/C++ won't do it for you. sizeof() works only when compiler knows the size, which is not true in dynamic arrays.

    And if you wan to achieve it with something more safe than dynamic arrays:

    #include 
    // ...
    
    std::vector> vect(10, std::vector(5));
    vect[3][2] = 1;
    

提交回复
热议问题