访问通过引用函数传递的双指针2d数组

时间:2014-09-20 10:06:36

标签: c pointers

我有这个数据结构

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++;
    }

   }

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

2 个答案:

答案 0 :(得分:1)

由于分配matrix_t的代码使用第一个n_rows的行数malloc,因此使用矩阵的代码需要按row的顺序传递索引,然后column。您的函数需要反转其索引,如下所示:

// 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

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

答案 1 :(得分:1)

您可能需要以下内容:

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 m;
m = matrix_alloc(10,20);
matrix_set_column(m, 123, 9, 20);
...

这将仅传递指针,因为matrix_t是指针类型。

相关问题