carraysmemory-managementmatrix-multiplicationtriangular

How to efficiently store a triangular matrix in memory?


I want to store a lower triangular matrix in memory, without storing all the zeros. The way I have implemented it is by allocating space for i + 1 elements on the ith row. However, I am new to dynamic memory allocation in C and something seems to be wrong with my first allocation.

int main ()
{
    int i, j;
    int **mat1;
    int dim;

    scanf("%d", &dim);
    *mat1 = (int**) calloc(dim, sizeof(int*));

    for(i = 0; i < dim; i++)
    mat1[i] = (int*) calloc(i + 1, sizeof(int));

    for(i = 0; i < dim; i++)
    {
        for(j = 0; j < i + 1; j++)
        {
            scanf("%d", &mat1[i][j]);
        }
    }

    /* Print the matrix without the zeros*/
    for(i = 0; i < dim; i++)
    {
        for(j = 0; j < (i + 1); j++)
        {
            printf("%d%c", mat1[i][j], j != (dim-1) ? ' ' : '\n');
        }
    }

    return 0;
}

Solution

  • mat1 = calloc(dim,sizeof(int*));
    

    mat1 is a double pointer.You need to allocate memory for your array of pointers and later you need to allocate memory to each of your pointers individually.No need to cast calloc()