繁体   English   中英

将结构矩阵传递给C中的函数

[英]Passing a matrix of structs to a function in C

我知道也有类似的问题,但是即使我已经阅读了2个小时,我仍然无法弄清楚。

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 fill(struct box* soup[], int length, int width, char* alphabet)

使用[][]时会出现错误,因为没有从struct box*struct box转换。

Array decays into pointers. 将单一维度数组传递给函数时,接收数组的函数可能如下所示

void fun(char a[10])    void fun(char a[])  void fun(char *a)
{                       {                   {
    ...             OR      ...         OR      ... 
}                       }                   }

Arrays decays into pointer, not always true ...数组衰减为指针的方法不是递归应用的...意味着, 2D数组会衰减到pointer to array不是pointer to pointer因此这就是您得到错误的原因。

2D数组传递给函数时,接收2D数组的函数应如下所示...

void fun(char *a[10])
{
    ...
}
 void fill(struct box**, int, int, char*); 

这个声明是错误的,因为它说函数的第一个参数必须是指向struct box指针类型,而您在main没有指向struct box的类型指针的对象,而是像您说的那样,结构的矩阵(二维数组,数组的数组)。

所以,原型

void fill(struct box [][], int, int, char *);

几乎是正确的,只是矩阵声明的主要(第一)维可以省略,因此我们需要至少指定其中的width ,该width也方便地传递给函数,只需要参数的顺序为进行更改,以便尽早定义width

void fill(int length, int width, struct box soup[][width], char *alphabet);

因此, main的函数调用为:

    fill(length, width, soup, alphabet);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM