我希望 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);
}
警告是:
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])
^
我还能如何将形式参数声明为常量?
最佳答案
我假设您不希望 foo() 能够为了封装而修改数组。
您可能已经知道,在 C 中,数组是通过引用传递给函数的。 因此,foo() 对值数组所做的任何更改都将传播回 main() 中的变量。这不利于封装。
const 不会阻止 foo() 修改数组 C 关键字 const 表示某些内容不可修改。 const 指针不能修改它指向的地址。该地址的值仍可以 修改。 在 c 中,默认情况下,您不能将新的指针值分配给数组名称。不需要常量。与 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);
}
我将 const 放在 foo() 定义中,因为您询问如何将形式参数声明为常量。它有效但不是必需的。
void foo(stct bar)
删除 const 不会破坏函数。
关于const array[][] 作为 C 中的形式参数 - 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29692390/