views:

429

answers:

6

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 array to a function that does the checking...

Currently I have such code for calling the function:

int squaretest(int **p, int n, int sum) {

    //some code
};

And this code is for creating the array:

int main() { 

    //some code. n - length of one row, sum - sum of elements in one row.
    int a; 
    int **lsquare;
    lsquare = new int*[n];
    for (int i=0;i<=n-1;i++) for (int j=0;j<=n-1;j++) {
     cin >>a;
     lsquare[i][j] = a;
    }
    blocktest(lsquare,n,sum);
    //some code
};

The code compiles (i am using Geany IDE and G++ compiler) but when I run it in terminal, after the first imput, that has to be stored in block[0][0] I get Segmentation fault error. What's wrong with my code and what is the correct sollution?

A: 

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
James Black
A: 

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++)
    {
    //...
Brian
A: 

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.

T.E.D.
+5  A: 

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);
sharth
A: 

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];
}
erelender
+2  A: 

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){...}
zufar