typedef struct { int num_rows; int num_cols; int** data; } BinaryMatrix; Impleme
ID: 3677060 • Letter: T
Question
typedef struct {
int num_rows;
int num_cols;
int** data;
} BinaryMatrix;
Implement function
voidUpdateEntry(BinaryMatrix*M,introw,intcol,intcontent);
Updates the (row, col)th entry of *Mwith content. Check that rowand colare valid indices for *M, and if not, print the error message ErrorinUpdateEntry:indexoutofbounds ending with a newline and exitthe program. Check that contentis a 0 or a 1, and if not, print the error message ErrorinUpdateEntry:contentmustbe0or1 ending with a newline and exitthe program.
Could anyone help me with this?
My attempt is
int i,j;
if (row> M->num_rows|| col> M->num_cols || row<0 || col <0 )
{
printf("Error in Update Entry: index out of bounds ");
return;
}
else
{
for (i=0; i<row; i++)
for (j=0; j<col; j++)
{
M->data[i][j]=content;
}
}
}
Explanation / Answer
Your first part is correct but second part is incorrect as the nested for loops will update all entries of the matrix with same content. Below is the updated code
int i,j;
if (row > M->num_rows || col > M->num_cols || row < 0 || col < 0 )
{
printf("Error in Update Entry: index out of bounds %d n ", row);
return;
}
if((content <0) || (content > 1))
{
printf("Error in Update Entry: content must be 0 or 1 %d ", content);
return;
}
else
{
M->data[row][col]=content;
}
Also you should b carefull while allocating memory to double pointer data as it can get confusing at times. Please run this code and reply back if you face any problem.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.