提供的程序完全不正确。可变长度数组可能没有静态存储持续时间/根据 C 标准(6.7.6.2 数组声明符)
2 如果一个标识符被声明为具有可变修改的类型,它
应该是一个普通的标识符(如 6.2.3 中定义的),没有链接,
并且具有块范围或函数原型范围。 如果
标识符被声明为具有静态或线程存储的对象
持续时间,它不应具有可变长度数组类型。
此外,指针类型double ** 和double ( * )[cols](如果正确声明的数组在表达式中转换为它们)不兼容。所以函数是错误的。
double** example(int rows, int cols){
static double tr[rows][cols];
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
tr[j][i] = 0;
return tr;
}
这是一个演示程序,展示了如何处理可变长度数组。
#include <stdio.h>
void init( size_t rows, size_t cols, double a[rows][cols] )
// or
// void init( size_t rows, size_t cols, double a[][cols] )
// or
// void init( size_t rows, size_t cols, double ( *a )[cols] )
{
for ( size_t i = 0; i < rows; i++ )
{
for ( size_t j = 0; j < cols; j++ ) a[i][j] = 0.0;
}
}
void display( size_t rows, size_t cols, double a[rows][cols] )
// or
// void display( size_t rows, size_t cols, double a[][cols] )
// or
// void display( size_t rows, size_t cols, double ( *a )[cols] )
{
for ( size_t i = 0; i < rows; i++ )
{
for ( size_t j = 0; j < cols; j++ ) printf( "%lf", a[i][j] );
putchar( '\n' );
}
}
int main(void)
{
while ( 1 )
{
size_t m, n;
printf( "Enter numbers of rows and columns (0 - exit): " );
if ( scanf( "%zu%zu", &m, &n ) != 2 || m == 0 || n == 0 ) break;
double a[m][n];
putchar( '\n' );
init( m, n, a );
display( m, n, a );
putchar( '\n' );
}
return 0;
}
它的输出可能看起来像
Enter numbers of rows and columns (0 - exit): 2 3
0.0000000.0000000.000000
0.0000000.0000000.000000
Enter numbers of rows and columns (0 - exit): 3 4
0.0000000.0000000.0000000.000000
0.0000000.0000000.0000000.000000
0.0000000.0000000.0000000.000000
Enter numbers of rows and columns (0 - exit): 0 0
在这两个函数中,第三个参数被调整为指针类型double ( *a )[cols]。和double **a不一样。
如果你会编写例如下面的程序
#include <stdio.h>
#define M 2
#define N 3
int main(void)
{
int a[M][N] =
{
{ 1, 2, 3 },
{ 4, 5, 6 }
};
int **p = ( int ** )a;
p[0][0] = 10;
return 0;
}
那么它将具有未定义的行为,因为p[0] 认为存储在元素a[0][0] 中的值(或存储在元素a[0][0] 和a[0][1] 中的组合值取决于指针的大小)即值1 作为指针值并尝试访问表达式 p[0][0] 中地址 1 处的内存。