为了练习c ++,我尝试了一些编码问题,但是我遇到了总线错误。 (我的代码编译得很好!)
这是我写的代码。
在我的main函数中,我调用test7()。 test7()基本上创建了一个4x3测试矩阵,用于测试函数zerotheMatrix()。 该函数查找的元素是' 0' 0并将整个行和列设置为0。
void zeroTheMatrix(int** matrix, int m, int n)
{
bool zeroRows[m];
bool zeroCols[n];
for(unsigned int g = 0; g < m; g++)
{
zeroRows[g] = false;
}
for(unsigned int g1 = 0; g1 < n; g1++)
{
zeroCols[g1] = false;
}
printf("Original matrix:\n");
for(unsigned int i = 0; i < m; i++)
{
for(unsigned int j = 0; j < n; j++)
{
printf("%i ", matrix[i][j]);
}
printf("\n");
}
for(unsigned int r = 0; r < m; r++)
{
for(unsigned int c = 0; c < n; c++)
{
if(matrix[r][c] == 0)
{
zeroRows[r] = 1;
zeroCols[c] = 1;
}
}
}
for(unsigned int r2 = 0; r2 < m; r2++)
{
for(unsigned int c2 = 0; c2 < n; c2++)
{
if(zeroRows[r2] == 1 || zeroCols[c2] == 1)
matrix[r2][c2] = 0;
}
}
printf("Zeroed matrix:\n");
for(unsigned int final = 0; final < m; final++)
{
for(unsigned int final2 = 0; final2 < n; final2++)
{
printf("%i ", matrix[final][final2]);
}
printf("\n");
}
}
void test7()
{
int row = 4;
int col = 3;
int **matrix;
for(unsigned int i = 0; i < row; i++) // n^2
{
unsigned int num = i*col;
matrix[i] = new int[col];
for(unsigned int j = 0; j < col; j++)
{
if( i != 0 && (j/i) > 1)
matrix[i][j] = 0;
else
matrix[i][j] = num;
num++;
//printf("matrix[%d][%d] = %d\n", i, j, matrix[i][j]);
}
}
zeroTheMatrix(matrix, row, col);
}
以下是终端的输出:
Original matrix:
0 1 2
3 4 0
6 7 8
9 10 11
Zeroed matrix:
0 0 0
0 0 0
0 7 0
0 10 0
Bus error: 10
谢谢