gpt4 book ai didi

c - 访问通过引用传递给函数的双指针二维数组

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

我有这个数据结构

struct m_bucket
{
int a;
int b;
};

然后我需要使用 struct m_bucket 的二维数组作为矩阵,所以我用这种方式声明它

typedef struct m_bucket **  matrix_t;

这是初始化函数

matrix_t matrix_alloc( int n_rows , int n_cols )
{
matrix_t m;
int i;

m = ( struct m_bucket **) malloc( ((n_rows + 1) * sizeof( struct m_bucket * )));

for(i=0 ; i < (n_rows + 1) ; i++ )
{
m[i] = ( struct m_bucket *) malloc( ((n_cols + 1) * sizeof( struct m_bucket )));
}

return m;
}

我的问题是,在通过引用函数传递数据结构时,我对访问该数据结构的正确方法有点困惑。我试过了,但没有用。

void matrix_set_column(matrix_t * matrix , int val , int col , int n_cols)
{
int i;

for(i = 0 ; i < (n_cols + 1) ; i++)
{
(*matrix)[col][i].cost = val;

if (val>0)
((*matrix)[col][i]).a = 4;
else
((*matrix)[col][i]).a = -1;
val++;
}

}

访问此结构的正确方法是什么?

最佳答案

由于分配matrix_t的代码使用第一个malloc的行数n_rows,所以使用矩阵的代码需要通过索引顺序为,然后是。您的函数需要反转其索引,如下所示:

// Assuming that col represents the column, not the row,
// i represents the row, so it needs to go first
((*matrix)[i][col]).a = 4;

索引 i 也需要从零到 n_rows+1

除此之外,您的代码没问题:您已正确添加括号以强制一元 *[] 运算符之前完成,因此其余代码没问题.

关于c - 访问通过引用传递给函数的双指针二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25947604/

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