我有一个函数需要一个数组作为参数,并在修改它后返回相同的数组。 编译给我一个错误,我传递参数并调用函数。 为什么会这样?
int solve(int a[9][9])
{
...
return a;
}
int main()
{
int a[9][9];
a = solve(a); <error here>
}
最佳答案
对于初学者来说,数组没有赋值运算符。数组指示符是不可修改的左值。
来自 C 标准(6.3.2.1 左值、数组和函数指示符)
- ... A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const qualified type.
其次,像数组一样声明的参数被调整为指向其元素类型的指针。
摘自 C 标准(6.7.6.3 函数声明符(包括原型(prototype)))
7 A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation...
例如这个函数声明
void f(int a[9][9]);
调整为
void f(int ( *a )[9]);
第三,函数不能以数组作为返回类型。但它们可能会返回指针。
来自 C 标准(6.9.1 函数定义)
3 The return type of a function shall be void or a complete object type other than array type.
例如,函数solve
可以声明为
int ( * solve(int a[9][9]) )[9]
{
// ...
return a;
}
如果函数在任何情况下都更改了数组的元素,那么编写就没有意义
int a[9][9];
a = solve(a);
你可以直接写
int a[9][9];
solve(a);
或
int a[9][9];
int ( *p )[9] = solve(a);
这是一个演示程序
#include <stdio.h>
#define M 2
#define N 3
int ( * f( int ( *a )[N], size_t n ) )[N]
{
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < N; j++ ) a[i][j] *= 10;
}
return a;
}
int main(void)
{
int a[M][N] =
{
{ 1, 2, 3 },
{ 4, 5, 6 }
};
f( a, M );
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", a[i][j] );
putchar( '\n' );
}
putchar( '\n' );
int ( *p )[N] = f( a, M );
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", p[i][j] );
putchar( '\n' );
}
putchar( '\n' );
f( p, M );
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", p[i][j] );
putchar( '\n' );
}
putchar( '\n' );
return 0;
}
它的输出是
10 20 30
40 50 60
100 200 300
400 500 600
1000 2000 3000
4000 5000 6000
为了简化函数声明,您可以引入 typedef 名称。
例如
typedef int( *PArray )[N];
PArray f( int ( *a )[N], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < N; j++ ) a[i][j] *= 10;
}
return a;
}
或者像这样
typedef int( *PArray )[N];
PArray f( PArray a, size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < N; j++ ) a[i][j] *= 10;
}
return a;
}
关于c - 如何在函数中传递和返回整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47871910/