Engaged in the study of the benefits after three years of Java (Android) Dynamic memory allocation

int N = 2; int **M = (int **) malloc(N * sizeof(int)); for (int i = 0; i < N; i++) { M[i] = (int *) malloc(N * sizeof(int)); } 

After this creation, I get an array of pointers M, in which the debager (in CLion) returns an infinite number of elements. And each of the elements contains an infinite number of intes. More precisely, pointers to them Explain, please, what is the number of elements? From the value of N, the number does not change. Are these pointers to memory outside of arrays?

  • As a recommendation, in most cases there is no point in manually allocating / freeing memory. For the same arrays there are std::vector and std::array . - Vladimir Gamalyan

2 answers 2

Question to debager: what does he show there. In fact, М is just a pointer, which is probably why he does not have any particular size available to the debager.

Try to declare an array and see what it says to it:

 int K[42]; 

In this case, the code you have an error. The first selection should be sizeof(int*) . Well, in addition, the pluses here do not smell. Pure C

    malloc and free in C ++ do not use - they are not compatible with the "native" new and delete . If you select something through malloc , and delete through delete , it will be UB. Therefore, it is safer to simply give up this couple. Moreover, foolish leapfrog with dimensions - see-see.

    “Correct” in terms of the standard and purity of the code, the manufacture of a two-dimensional array:

     #include <iostream> #include <vector> using std::vector; using std::cout; using std::endl; int main() { constexpr size_t M=10; //count of rows constexpr size_t N=12; //count of cols constexpr int v=42; //initial value vector<vector<int>> alpha( M, //count of rows vector<int>( //initial row N, //count of cols v //initial value ) ); for(const auto& i:alpha) { for(const auto& j:i) { cout << j << ' '; } cout << endl; } return 0; } 

    IDEONE