The C problem is asked to Dynamically allocates a new BinaryMatrix with num_rows
ID: 3677042 • Letter: T
Question
The C problem is asked to
Dynamically allocates a new BinaryMatrix with num_rows rows and num_cols cols. Each entry of the matrix should be 0.
Check that num_rowsand num_colsare greater than 0, and if not, print the error message
ErrorinCreateMatrix:numberofrowsandcolumnsmustbe positive
ending with a newline and exitthe program.
Then I have another function void DeleteBinaryMatrix(BinaryMatrix* M). Could you also implement the function to deallocates the memory used for *M.
My struct is
typedef struct {
int num_rows;
int num_cols;
int** data;
} BinaryMatrix;
Could anyone please help me fix the code or write a new one for me please? Thanks.
BinaryMatrix* ConstructBinaryMatrix(int num_rows, int num_cols) {
BinaryMatrix* temp;
BinaryMatrix* M=(BinaryMatrix*)malloc(sizeof(BinaryMatrix));
int c,r;
M->data[c][d];
M->data=(BinaryMatrix**)malloc(sizeof(BinaryMatrix*));
for (int c=0; c< M->num_cols; c++){
M->data[c]=(char*)malloc(M->num_cols*sizeof(char));
}
for (int r=0; r< M->num_rows; r++){
M->data[r]=(char*)malloc(M->num_rows*sizeof(char));
}
if (num_rows<=0 || num_cols<=0)
{
printf("Error in CreateMatrix: number of rows and columns must be positive ");
exit;
}
else
{
int i=0, j=0;
for (i=0; i
for (j=0; j
{
(*temp).data=0;
}
}
}
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int num_rows;
int num_cols;
int** data;
} BinaryMatrix;
BinaryMatrix* ConstructBinaryMatrix(int num_rows, int num_cols) {
int c;
BinaryMatrix* M;
M =(BinaryMatrix*)malloc(sizeof(BinaryMatrix));
M->num_rows = num_rows;
M->num_cols = num_cols;
M->data = (int **) malloc (num_rows*sizeof(int *));
for (c=0; c< M->num_cols; c++){
M->data[c]=(int*)malloc(sizeof(int));
}
if (num_rows<=0 || num_cols<=0)
{
printf("Error in CreateMatrix: number of rows and columns must be positive ");
exit(0);
}
else
{
int i,j;
for( i=0; i<M->num_rows; i++){
for( j=0; j<M->num_cols; j++)
M->data[i][j] = 0;
}
}
return M;
}
void DeleteBinaryMatrix(BinaryMatrix* M){
int i;
// deleting each row
for(i=0; i<M->num_rows; i++){
free(M->data[i]);
}
// deleting data
free(M->data);
// deleting M
free(M);
}
/* Driver program to check above functions */
int main()
{
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.