我正在通过88 C程序工作,在将近二十五年之后重新学习C(由于自1990年以来至少对该语言本身进行了两次主要版本修订这一事实很复杂,我确信Turbo-C我当时用的并不完全兼容C89).我不记得我所用的类对二维数组做了什么后果,并将它们传递给函数,期望我需要在不知道编译时的维数的情况下处理数据,这很好.我的头爆炸了.
我正在使用gcc(目前在Ubuntu 14.04的标准存储库中找到的版本),我收集它应该支持C99或C2011标准下的可变长度数组声明,但是我试图用来制作函数的声明识别数组而不必知道编译时的大小是否有关于"冲突类型"的错误.我正在编写警告设置为max,使用一个小的Python程序来节省每次我需要编译时输入一个长命令行(结果命令是gcc -std=c99 -pedantic -Wall -Wextra -o target target.c -lm).以下是原型,来电线和功能定义(代码中充满了警告,导致不良做法,我从书中复制了它;我现在不关心那些,我对学习感兴趣这样做的理智方式,所以我不必使用那些丑陋,令人困惑的方法).
#include <stdio.h>
#include <stdlib.h>
/* ANSI prototypes */
void s2 (int, int, int*);
int main (void);
int main (void)
{
int one[5]={0,1,2,3,4};
int two[3][4] =
{
{0,1,2,3},
{10,11,12,13},
{100,101,102,103}
};
/* try to call s2, it won't work */
printf("\ncalling s2 \n");
s2(1, 5, one);
s2(3, 4, two); /* will be compiler warning */
}
void s2(int rows, int cols, int *x[rows][cols])
{
/* wants to use multiple square brackets; needs dimension info */
int i,j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
printf("%4i", x[i][j]);
}
}
Run Code Online (Sandbox Code Playgroud)
这会给出以下警告和错误字符串:
./gccm sotest
sotest.c: In function ‘main’:
sotest.c:22:3: warning: passing argument 3 of ‘s2’ from incompatible pointer type [enabled by default]
s2(3, 4, two); /* will be compiler warning */
^
sotest.c:6:6: note: expected ‘int *’ but argument is of type ‘int (*)[4]’
void s2 (int, int, int*);
^
sotest.c: At top level:
sotest.c:25:6: error: conflicting types for ‘s2’
void s2(int rows, int cols, int *x[rows][cols])
^
sotest.c:6:6: note: previous declaration of ‘s2’ was here
void s2 (int, int, int*);
^
sotest.c: In function ‘s2’:
sotest.c:32:7: warning: format ‘%i’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%4i", x[i][j]);
^
Run Code Online (Sandbox Code Playgroud)
我花了至少几个小时在这里挖掘其他类似看似的问题,在网上阅读文章,并且通常试图将我的大脑包围在你需要将二维数组传递给一个二维数组时出现的疯狂. C中的函数 - 它在许多其他语言中如此简单,并且在C中一维数组很容易!我找不到任何有意义的东西; 我见过的唯一明智的建议就是将数组包装成a Struct,但是在前20年左右肯定不存在的那些C被广泛使用,我不确定如何/为什么这样做会更好.
您的声明应如下所示:
void s2(int rows, int cols, int x[rows][cols]);
该函数采用二维整数数组.使用该声明,您使用变量2进行调用即可.你使用变量1调用是错误的,因为只有一个维度.
另外,确保您的声明和函数匹配,然后您的函数需要如下所示:
void s2(int rows, int cols, int x[rows][cols])
{