如何有效地将三角矩阵存储在内存中? [英] How to efficiently store a triangular matrix in memory?
本文介绍了如何有效地将三角矩阵存储在内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想存储下三角矩阵在内存中,而不存储所有零.我实现它的方法是在第 i 行上为 i + 1
元素分配空间.但是,我是C语言中动态内存分配的新手,第一次分配似乎有些问题.
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 i
th 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;
}
推荐答案
mat1 = calloc(dim,sizeof(int*));
mat1
是双指针.您需要为指针数组分配内存,然后需要分别为每个指针分配内存.无需强制转换 calloc()
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()
这篇关于如何有效地将三角矩阵存储在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文