Using dynamic multi-dimensional arrays in c++

后端 未结 6 500
礼貌的吻别
礼貌的吻别 2020-12-21 01:24

I am making a C++ program that checks if given aray is a latin square. I need to use a dynamic multi-dimensional array that stores given latin square. But I cant pass the ar

相关标签:
6条回答
  • 2020-12-21 01:35

    You forgot to allocate memory for second dimension of the matrix.

    int **lsquare;
    lsquare = new int*[n];
    for (int i=0; i<n; ++i){
      lsquare[i] = new int[n];
    ....}
    

    nobody writes

    for (int i=0;i<=n-1;i++){...}
    

    Do instead

    for (int i=0; i<n; ++i){...}
    
    0 讨论(0)
  • 2020-12-21 01:44

    You have to allocate space for the second dimension too, add this after you allocate lsquare:

    for(int i = 0; i < n; ++i)
    {
        lsquare[i] = new int[n];
    }
    
    0 讨论(0)
  • 2020-12-21 01:46

    To be able to do that.. You actually need to do this:

    int **lsquare = new int*[n];
    
    for (int i=0; i<n; ++i)
        lquare[i] = new int[n];
    
    for (int i=0; i<n; i++)
        for (int j=0; j<n; j++)
            cin >> lsquare[i][j];
    
    blocktest(lsquare,n,sum);
    

    The better system would be to do:

    int *lsquare = new int[n*n];
    
    for (int i=0; i<n; ++i)
        for (int j=0; j<n; ++j)
            cin >> lsquare[i + j*n];
    
    blocktest(lsquare, n, sum);
    
    0 讨论(0)
  • 2020-12-21 01:49

    You made yourself a pointer pointer that can be used as a matrix, allocated one row for it, then proceeded to act like you'd allocated an entire n*n matrix. You will indeed get a segfault if you run that.

    You need to allocate enough space for n*n elements, not just n of them.

    A less error-prone solution might be to use a std::vector of std::vectors.

    0 讨论(0)
  • 2020-12-21 01:54

    You have an array of pointers in lsquare.

    You might want to just do something like:

    lsquare = new int[n * n];
    

    That way you can then fill in this square, but the type is then:

    int *lsquare
    
    0 讨论(0)
  • 2020-12-21 02:00

    What you are actually creating an array of arrays. Not only do you need to allocate the array of arrays using new, but also you must allocate all n arrays. You'll want to have the outer loop of your nested for loop allocate each of the n sub-arrays.

    lsquare = new int*[n];
    for (int i=0;i<=n-1;i++) 
    {
        lsquare[i] = new int[n];
        for (int j = 0;j<=n-1;j++)
        {
        //...
    
    0 讨论(0)
提交回复
热议问题