提交的程序完全不正确。可变长度阵列可以不具有静态存储持续时间/按照C标准(6.7.6.2组声明)
2如果identi音响ER被声明为具有可变MODI音响版型,它 应是一个普通的identi音响ER(如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
不一样。
如果将例如因为p[0]
认为a[0][1]
取决于存储在元素a[0][0]
的值(或者存储在元件组合的值a[0][0]
和编写以下程序
#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;
}
那么它将有不确定的操作指针大小),即值1作为指针值,并尝试访问表达式p[0][0]
中地址1处的内存。
'example'返回一个双指向第一个元素的指针。你可以用同样的方式访问它的元素,即'tr [0] [1]'< - 行0,列1。 – Geoff
扔掉这本书,它教你*垃圾*。请参阅下面的Vlad的答案。 'double **'不是*返回二维数组的正确类型。 –