Reputation:
typedef struct {
int num_rows;
int num_cols;
int** data;
} BinaryMatrix;
BinaryMatrix *ConstructBinaryMatrix(int num_rows, int num_cols) {
BinaryMatrix matrix = {
.num_rows = num_rows,
.num_cols = num_cols,
.data = (int **) malloc((num_rows) * sizeof(int *)),
};
int i;
for (i = 0; i < num_cols; i++) {
matrix.data[i] = (int *) malloc(num_cols * sizeof(int));
}
return &matrix;
}
Is this the correct way to define a BinaryMatrix, and how to initialize it?
Thanks for your help.
I got the following error.
BinaryMatrix* M;
M = ConstructBinaryMatrix(2, 2);
printf("%d:%d", M->num_rows, M->num_cols);
The output is: 4198012:0
Upvotes: 0
Views: 144
Reputation: 48043
You are returning a pointer to local data, which is bad form and doesn't work.
You should probably call malloc
to allocate space for a BinaryMatrix structure, something like this:
BinaryMatrix *ConstructBinaryMatrix(int num_rows, int num_cols) {
BinaryMatrix *matrix = malloc(sizeof(BinaryMatrix));
matrix->num_rows = num_rows;
matrix->num_cols = num_cols,
matrix->data = malloc(num_rows * sizeof(int *));
int i;
for (i = 0; i < num_rows; i++) {
matrix->data[i] = malloc(num_cols * sizeof(int));
}
return matrix;
}
(Also I have fixed the loop bounds, as M.M. pointed out.)
Upvotes: 2
Reputation: 505
Unless its very large I would use:
#define M 3
#define N 3
int matrix[M][N]={{0,0,0},{0,0,0},{0,0,0}};
/* above possibly static */
Simples !
If the matrix was large simply use for loops to initialize.
Upvotes: -2
Reputation: 141648
i < num_cols
should be i < num_rows
.
Currently your code returns the address of a local variable. Local variables are destroyed when the function returns, so you in fact return a dangling pointer, not a good idea.
Instead you should return a copy of the local variable. Remove the *
from the function prototype and from declaration of M
, and remove the &
from the return
statement.
Upvotes: 1