gpt4 book ai didi

c - 如何为矩阵中的特定元素动态分配内存?

转载 作者:太空宇宙 更新时间:2023-11-04 07:50:25 25 4
gpt4 key购买 nike

1 2 0 0 0
0 2 3 0 0
0 0 4 5 0
0 0 0 5 6
0 0 0 0 7

我正在尝试以这种格式分配一个矩阵,但不应动态分配等于 0 的元素。而且这种分配需要高效。

最佳答案

下面是一个可能的解决方案示例,可帮助您入门。其他方法也是可能的。此代码未经测试。

#include <stdlib.h>

typedef float T;

// Attempt to allocate space for a bidiagonal matrix of size n-by-n.
T *MallocBidiagonalMatrix(size_t n) { return malloc((2*n-1) * sizeof(T)); }

// Free a bidiagonal matrix.
void FreeBidiagonalMatrix(T *p) { free(p); }

// Return a reference to element [r, c] of bidiagonal matrix p of size n-by-n.
T *BidiagonalMatrixElement(size_t n, T *p, size_t r, size_t c)
{
static T Zero = 0;

// The diagonal elements are stored from p[0] to p[n-1].
if (r == c)
return p+r;

// The existing off-diagonal elements are stored from p[n] to p[2*n-2].
if (r == c-1)
return p+n+r;

/* For non-existing (zero) elements, return a reference to zero. (Callers
are expected not to write to this address. If they do, the behavior is
not defined.)
*/
else
return &Zero;
}

/* Show how a bidiagonal matrix previously allocated with
MallocBidiagonalMatrix might be initialized.
*/
void InitializeBidiagonalMatrix(size_t n, T *p)
{
// Initialize the diagonal elements.
for (size_t i = 0; i < n; ++i)
*BidiagonalMatrixElement(n, p, i, i) = rand();

// Initialize the off-diagonal elements.
for (size_t i = 0; i < n-1; ++i)
*BidiagonalMatrixElement(n, p, i, i+1) = rand();
}

/* Show how a bidiagonal matrix might be used in arithmetic by demonstrating
a simple matrix addition. The n-by-n bidiagonal matrix p is added to
n-by-n matrix q.
*/
void AddBidiagonalMatrixToDenseMatrix(size_t n, T *p, T (*q)[n])
{
for (size_t r = 0; r < n; ++r)
for (size_t c = 0; c < n; ++c)
q[r][c] += *BidiagonalMatrixElement(n, p, r, c);
}

请注意,AddBidiagonalMatrixToDenseMatrix 可以优化为只处理存储的元素。但是,给定的实现演示了一种算法如何运行,而无需考虑实际存储的元素。

关于c - 如何为矩阵中的特定元素动态分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54241863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com