Reputation: 976
i've this data structure
struct m_bucket
{
int a;
int b;
};
then i need to use a 2D array of struct m_bucket
as a matrix so i declare it on this way
typedef struct m_bucket ** matrix_t;
and this is the initialization function
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;
}
my problem is that i'm a bit confused about the right way to acces this data structure when passing it by reference to a function. I tried this but it isn't working.
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++;
}
}
what's the right way to access this structure?
Upvotes: 1
Views: 628
Reputation: 726489
Since the code that allocates matrix_t
uses the number of rows n_rows
for the first malloc
, the code that uses the matrix needs to pass indexes in the order row
, then column
. Your function needs to reverse its indexes, like this:
// Assuming that col represents the column, not the row,
// i represents the row, so it needs to go first
((*matrix)[i][col]).a = 4;
Index i
needs to from zero to n_rows+1
, too.
Other than that, your code is fine: you have correctly added parentheses to force unary *
to complete before []
operator, so the rest of the code is OK.
Upvotes: 1
Reputation: 7472
You probably want the following:
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++;
}
}
and use it as:
...
matrix_t m;
m = matrix_alloc(10,20);
matrix_set_column(m, 123, 9, 20);
...
This will pass only pointers, because matrix_t
is a pointer type.
Upvotes: 1