c - 我得到 "incompatible pointer type",我不明白为什么

标签 c pointers

我遇到两种类型的错误:

编译器的提示

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++ 确实允许这种转换)。

你有两个选择,都没有吸引力:

  1. 让函数接受 int 而不是 const int
  2. 在调用 const int 函数时写一个转换,例如printMatrix((const int (*)[MAXCOL])m, 5, 5);

通常会使用选项 1,我们只需要在没有多维数组的常量正确性的情况下就可以了。

关于c - 我得到 "incompatible pointer type",我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33726130/

相关文章:

在 ANSI C 中转换动态分配的任意指针数组

c - Win32 - 在纯 C 中分离多个加载的 DLL 实例中的数据

c - 正确使用文件指针

c++ - 使用紧凑指针表示法结束多维数组

c - C中数组的地址等于它的第一个元素吗

c++ - 从 C 文件调用 C++ 标准头 (cstdint)

c - 我们如何将 FILE* 转换为 HANDLE?

c - 使用 fwrite 将由标记分隔的多个字符串打印到二进制文件中

c - 为二维整数数组分配内存,但它应该是连续的

c - memcpy c 中的 3d 指针