how to use int ** instead of int [][] two dimensional array

202 views Asked by At
typedef struct{
       int rows, cols;    // matrix dimensions
       int **element;     // element array
}Matrix;

If i were to create a variable:

Matrix m;

How would i go about creating a 3x3 {{1,2,3},{4,5,6},{7,8,9}} array in the Matrix? Or for that matter, how could i store any sized two-dimensional array into m.element?

I have tried:

for (i=0; i<m.rows; i++)
{
    for (k=0; k<m.cols; k++)
    {
        m.element=q;
        q++;
    }
}
3

There are 3 answers

2
randomusername On

Follow the advice of the comment and look at Dynamic Allocation of 2D Array

Then do

for (i = 0; i < m.rows; i++) {
  for (j = 0; j < m.cols; j++) {
    m.element[i][j] = q++;
  }
}

You need to add in the m.element[i][j] part to make it work.

5
benipalj On

Although, you should'nt use pointer to pointer for storing 2-D array, but you can do something like:

m.element = malloc(sizeof(int*)*3);
for (int j=0;j<3;++j)
{
    m.element[j] = malloc(sizeof(int)*3);
}
1
Eric Jablow On

You need to allocate space for the matrix. Simply assigning values to m.elements[i][j] will do attempt to access memory at unknown locations, as m.elements will be uninitialized and will have essentially random values. Your program may not be able to access it, or it might not be aligned properly. Build a function to create a rows × cols matrix:

// Initialize and return a passed-in matrix.
// matrix must point to an allocated struct, not NULL.
void build(Matrix * const matrix, const size_t rows, const size_t cols) {
    matrix->rows = rows;
    matrix->cols = cols;
    matrix->elements = malloc(rows * sizeof(int *));
    for (size_t row = 0; row < rows; row++) {
        matrix->elements[row] = malloc(cols * sizeof(int));
    }
}

Note that you can create arrays of any shape. If you need to create symmetric matrices, you need only store items not below the main diagonal.

Since this dynamically allocates the 2-dimensional array, it's your responsibility to free it when you are done:

void destroy(Matrix * const matrix) {
    for (size_t row = 0; row < matrix->rows; row++) {
        free(matrix->elements[row]);
    }
    free(matrix->elements);
}