将结构矩阵传递给C中的函数
我知道也有类似的问题,但我还是不明白,尽管我已经读了两个小时了将结构矩阵传递给C中的函数,c,matrix,struct,C,Matrix,Struct,我知道也有类似的问题,但我还是不明白,尽管我已经读了两个小时了 struct box { char letter; int occupied; //0 false, 1 true. }; void fill(struct box**, int, int, char*); //ERROR HERE** int main(int argc, char** argv) { int length=atoi(argv[4]), width=a
struct box
{
char letter;
int occupied; //0 false, 1 true.
};
void fill(struct box**, int, int, char*); //ERROR HERE**
int main(int argc, char** argv)
{
int length=atoi(argv[4]),
width=atoi(argv[5]),
char alphabet[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
struct box soup[length][width];
fill(soup, length, width, alphabet); //HERE**
}
void fill(struct box soup[][], int length, int width, char*alphabet) //AND HERE**
{
//omitted
}
以下是我编译时遇到的错误:
warning: passing argument 1 of ‘fill’ from incompatible pointer type [enabled by default]
fill(soup, length, width, alphabet);
^
note: expected ‘struct box **’ but argument is of type ‘struct box (*)[(sizetype)(width)]’
void fill(struct box **, int, int, char*);
^
error: array type has incomplete element type
void fill(struct box soup[][], int length, int width, char*alphabet)
^
我不明白为什么它会失败,而我的其他一些功能,比如这一个,确实可以工作:
void wordsToMemory(char**, char*); //prototype
char* dictionary[Nwords];
wordsToMemory(dictionary, argv[1]); //calling the method
void wordsToMemory(char* dictionary[], char* argv) //function body
{
//omitted
}
这将使它能够编译:
void fill(struct box** soup, int length, int width, char* alphabet)
或
使用[][]时会出现错误,因为没有从结构框*到结构框的转换。数组会衰减为指针。将一维数组传递给函数时,接收数组的函数可以如下所示
void fun(char a[10]) void fun(char a[]) void fun(char *a)
{ { {
... OR ... OR ...
} } }
数组衰减为指针,不总是真的…数组衰减为指针不是递归应用的…意味着,2D数组衰减为指向数组的指针,而不是指向指针的指针,所以这就是为什么会出现错误
将2D数组传递给函数时,接收2D数组的函数应如下所示
void fun(char *a[10])
{
...
}
这个声明是错误的,因为它说函数的第一个参数必须是指向指向结构框的指针类型,而在main中没有指向结构框的指针类型的对象可供引用,相反,正如您所说,您有一个矩阵、一个二维数组、一个结构数组数组
那么,原型呢
void fill(struct box [][], int, int, char *);
几乎是正确的,除了,只有矩阵声明的第一维度的主要部分可以省略,因此我们需要至少指定其中的宽度,该宽度也可以方便地传递给函数,只需更改参数的顺序,以便尽早定义宽度:
void fill(int length, int width, struct box soup[][width], char *alphabet);
因此,main中的函数调用是:
fill(length, width, soup, alphabet);
您必须有一个奇怪的编译器,它接受一个函数参数,类型为array of length array of width struct box,类型为pointer to pointer to struct box,或者您只是没有尝试编译它;函数是void funchar*a[10]或void funchar a[][10]。
void fill(int length, int width, struct box soup[][width], char *alphabet);
fill(length, width, soup, alphabet);