const array [] []作为C - 不匹配中的形式参数

use*_*554 5 c const-correctness multidimensional-array

我希望foo()不要修改数组.所以我把数组声明foo()const

如果我编译这段代码,编译器就会抱怨:

#include <stdio.h>

void foo(const int arr[5][5])
{
    int i,j;
    for( i = 0; i < 5; i++)
    {   
        for( j = 0; j < 5; j++) 
        {       
            printf("%d\n", arr[i][j]);
        }       
    }   
}
int main()
{
    int val = 0;
    int i,j;
    int arr[5][5];
    for( i = 0; i < 5; i++)
    {   
        for( j = 0; j < 5; j++) 
        {       
            arr[i][j] = val++;
        }       
    }   
    foo(arr);
}
Run Code Online (Sandbox Code Playgroud)

警告是:

allocate.c: In function 'main':
allocate.c:26:9: warning: passing argument 1 of 'foo' from incompatible pointer type
     foo(arr);
         ^
allocate.c:3:6: note: expected 'const int (*)[5]' but argument is of type 'int (*)[5]'
 void foo(const int arr[5][5])
      ^
Run Code Online (Sandbox Code Playgroud)

我怎样才能将形式参数声明为常量?

小智 -1

我假设您不希望 foo() 能够为了封装而修改数组。

您可能知道,在 C 中数组是通过引用传递给函数的。因此,foo() 对值数组所做的任何更改都将传播回 main() 中的变量。这不利于封装。

const 不会阻止 foo() 修改数组 C 关键字 const 意味着某些内容是不可修改的。const 指针不能修改它指向的地址。该地址处的值仍然可以修改。在c中,默认情况下,您不能将新的指针值分配给数组名称。不需要 const。与 const 指针类似,该数组中的值仍然可以修改。封装问题没有解决。

要从 main() 函数封装 foo() ,请将数组放入结构中。结构体按值传递,因此 foo() 将接收数据的副本。由于它有一个副本, foo() 将无法更改原始数据。您的功能已被封装。

解决方案(有效!):

#include <stdio.h>

typedef struct
{
    int arr[5][5];
} stct;

void foo(const stct bar)
{
    int i,j;
    for( i = 0; i < 5; i++)
    {   
        for( j = 0; j < 5; j++) 
        {       
            printf("%d\n", bar.arr[i][j]);
        }       
    }   
}
int main()
{
    int val = 0;
    int i,j;
    stct bar;
    for( i = 0; i < 5; i++)
    {   
        for( j = 0; j < 5; j++) 
        {       
            bar.arr[i][j] = val++;
        }       
    }   
    foo(bar);
}
Run Code Online (Sandbox Code Playgroud)

我将 const 放在 foo() 定义中,因为您询问如何将形式参数声明为常量。它有效但不是必需的。

void foo(stct bar)
Run Code Online (Sandbox Code Playgroud)

删除 const 不会破坏该函数。