目前即使我把书上的例子照抄一遍,比如这个声明: int sum2d(int rows, int cols, int ar[rows][cols]); VC++的编译器还是显示错误,请问该如何解决呢
书上的例子:
#include <stdio.h>
int sum2d(int rows, int cols, int ar[rows][cols])
{
int r;
int c;
int tot = 0;
for(r=0; r<rows; r++)
for(c=0; c<cols; c++)
tot += ar[r][c];
return tot;
}
编译结果:
D:\VC++\chapter 10\test\est.cpp(2) : error C2057: expected constant expression
D:\VC++\chapter 10\test\est.cpp(2) : error C2466: cannot allocate an array of constant size 0
D:\VC++\chapter 10\test\est.cpp(2) : error C2057: expected constant expression
D:\VC++\chapter 10\test\est.cpp(2) : error C2466: cannot allocate an array of constant size 0
D:\VC++\chapter 10\test\est.cpp(2) : error C2087: '<Unknown>' : missing subscript
Error executing cl.exe.
test.exe - 5 error(s), 0 warning(s)
声明 带有二维数组做参数的函数,我知道第二维必须是常数,不过书中介绍 变长数组那一节,有两句话:1、创建一个处理任意二维数组的函数,也是有可能的,但是比较繁琐(因为这样的函数需要把数组当做一维数组传递,然后由函数计算每行的起始地址);2、C99标准引入了变长数组,它允许使用变量定义数组各维。(出自 C Primer Plus 第五版)然后我就抄下那段程式尝试编译。书上还有一段vararr2d.c的程序比较长我弄不上来,但也失败
追答如果非要用两个维数都是变长的二维数组,那参数就用指针吧,再另外加上两个参数指明各个维数,然后程序中自己为二维数组寻址。
函数改为sum2d(int rows, int cols, int **ar),ar[r][c]改为 *((int*)ar +rows*r + c)。
这个是不是因为VC++ 不支持C99 引入变长数组这一块啊?没想过还可以这么写 *((int*)ar +rows*r + c),受教了谢谢
追答不用客气,互相讨论,共同进步,呵呵
本回答被提问者和网友采纳