我试图用C编写两个函数。
第一个是获取两个矩阵(及其大小)并返回其多个矩阵的函数。
第二个是获取矩阵及其大小并打印的函数。
这两个函数都不会更改输入矩阵,因此我想在函数中将它们作为const获得(但在主主题上,而不是const矩阵)。
输出很好,但是编译器向我抛出警告(如下所示),所有这些,当我删除函数中的const声明时,不会向我抛出任何警告。
有人知道为什么向我抛出那些警告吗?我该如何解决? (我需要修复它吗?)
谢谢
#include <stdio.h>
#include <stdlib.h>
int** multiple_matrix(int row1, int column1, int row2, int column2 ,const int mat1[][column1], const int mat2[][column2])
{
if((mat1 == NULL) || (mat2 == NULL))
{
printf("matrix equal to NULL, can't multiple!!!\n");
return NULL;
}
if (row2 != column1)
{
printf("number of columns in the first matrix is not equal to number of rows in second matrix, can't multiple!!! \n");
return NULL;
}
int i,k,j,sum;
int** res_mat = malloc (sizeof(int*) * row1);
for (i = 0; i<row1; ++i)
{
res_mat[i] = malloc (sizeof(int) * column2);
for (j = 0; j < column2; ++j)
{
sum = 0;
for (k = 0; k < column1; ++k)
{
sum += mat1[i][k] * mat2[k][j];
}
res_mat[i][j] = sum;
}
}
return res_mat;
}
void print_matrix( int** mat,size_t row, size_t column)
{
if(mat != NULL)
{
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
printf("%d ",mat[i][j]);
}
printf("\n");
}
}
else
{
printf("matrix is Null\n");
}
}
int main()
{
int matrix1[][3] ={{1,2,9},{3,4,9},{5,6,9}};
int matrix2[][3] = {{7,8,9},{10,11,12},{1,1,1}};
int matrix3[][1] ={{20},{30}};
int ** matrix4 =NULL;
size_t row1 = sizeof(matrix1)/sizeof(matrix1[0]);
size_t column1 = sizeof(matrix1[0])/sizeof(matrix1[0][0]);
size_t row2 = sizeof(matrix2)/sizeof(matrix2[0]);
size_t column2 = sizeof(matrix2[0])/sizeof(matrix2[0][0]);
size_t row3 = sizeof(matrix3)/sizeof(matrix3[0]);
size_t column3 = sizeof(matrix3[0])/sizeof(matrix3[0][0]);
printf("matrix1 is: %zu X %zu\n" ,row1,column1);
printf("matrix2 is: %zu X %zu\n" ,row2,column2);
printf("matrix3 is: %zu X %zu \n\n" ,row3,column3);
int** res1_matrix = multiple_matrix(row1,column1,row2,column2, matrix1, matrix2);
printf("Matrix1 X Matrix2:\n");
print_matrix(res1_matrix, row1, column2);
printf("\n\n");
int** res2_matrix = multiple_matrix(row1,column1,row3,column3, matrix1, matrix3);
printf("Matrix1 X Matrix3:\n");
print_matrix(res2_matrix, row1, column3);
printf("\n\n");
return 0;
}
the warnings that I get when I use the const in the functions