Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dynamic multi-dimensional arrays in c++

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?

like image 416
skazhy Avatar asked Sep 24 '09 13:09

skazhy


People also ask

Can we use multi-dimensional array in C?

Multidimensional Arrays in C / C++ A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order.

What is the use of dynamic array in C?

Dynamic arrays are resizable and provide random access for their elements. They can be initialized with variable size, and their size can be modified later in the program. Dynamic arrays are allocated on the heap, whereas VLAs are allocated on the stack.

Can you make a dynamic array in C?

We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.

How do you dynamically allocate a 2D array?

A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.


2 Answers

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);
like image 140
Bill Lynch Avatar answered Oct 13 '22 20:10

Bill Lynch


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){...}
like image 2
zufar Avatar answered Oct 13 '22 20:10

zufar