我遇到两种类型的错误:
编译器的提示
pr.c: In function ‘main’:
pr.c:20:2: warning: passing argument 1 of ‘printMatrix’ from incompatible pointer type [enabled by default]
pr.c:9:6: note: expected ‘const int (*)[80]’ but argument is of type ‘int (*)[80]’
pr.c:22:2: warning: passing argument 1 of ‘lights’ from incompatible pointer type [enabled by default]
pr.c:10:6: note: expected ‘const int (*)[80]’ but argument is of type ‘int (*)[80]’
编译器似乎提示在接受 const 的函数中接收到非常量,但我被告知这是使用 const
的正确方法...
#include <stdio.h>
#include <stdlib.h>
#define MAXCOL 80
#define MAXROW 20
#define randNormalize() srand(time(0))
void fillMatrix(int m[][MAXCOL], size_t rows, size_t cols);
void printMatrix(const int m[][MAXCOL], size_t rows, size_t cols);
void lights(const int m[][MAXCOL], size_t rows, size_t cols);
int star(const int m[][MAXCOL], int row, int col);
int main()
{
int m[MAXROW][MAXCOL];
randNormalize();
fillMatrix(m, 5, 5);
printMatrix(m, 5, 5);
lights(m, 5, 5);
return 0;
}
void fillMatrix(int m[][MAXCOL], size_t rows, size_t cols)
{
int i, j;
for(i = 0; i < rows; i++)
for(j = 0; j < cols; j++)
m[i][j] = rand()%21;
}
void printMatrix(const int m[][MAXCOL], size_t rows, size_t cols)
{
int i, j;
for(i = 0; i < rows; i++)
{
printf("\n");
for(j = 0; j < cols; j++)
printf("%d ", m[i][j]);
}
printf("\n");
}
void lights(const int m[][MAXCOL], size_t rows, size_t cols)
{
int i, j;
for(i = 1; i < rows - 1; i++)
{
printf("\n");
for(j = 1; j < cols - 1; j++)
{
if( star(m, i, j) )
printf("*");
else
printf(" ");
}
}
printf("\n");
}
int star(const int m[][MAXCOL], int row, int col)
{
int i, j;
int sum = 0;
for(i = row - 1; i <= row + 1; i++)
for(j = col - 1 ; j <= col + 1; j++ )
sum += m[i][j];
return (sum/9 > 10);
}
我正在寻找不使用指针的最佳解决方案,因为这是来 self 们尚未涵盖它们的类(class)练习(尽管我已经研究过它们)。
最佳答案
不幸的是,在 C 中没有从 int[X][Y]
到 const int[X][Y]
的隐式转换。也不存在从 int (*)[Y]
到 const int (*)[Y]
的隐式转换。
这是语言的缺陷;没有技术原因不允许这样的转换。 (C++ 确实允许这种转换)。
你有两个选择,都没有吸引力:
- 让函数接受
int
而不是const int
- 在调用
const int
函数时写一个转换,例如printMatrix((const int (*)[MAXCOL])m, 5, 5);
通常会使用选项 1
,我们只需要在没有多维数组的常量正确性的情况下就可以了。
关于c - 我得到 "incompatible pointer type",我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33726130/