2013-12-18 57 views
0

我知道有类似的问题,但我仍然无法弄清楚,即使我已经阅读了2个小时。将结构矩阵传递给函数C

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 
} 
+1

http:// stackoverflow。com/questions/897366/how-do-pointer-to-pointers-work-in-c –

回答

0

这将使它能够通过编译:

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

+0

你必须有一个奇怪的编译器,它接受一个类型为_array的函数参数,它的长度是'width'数组''struct_frame'_对于_pointer类型的形式参数指向'struct box'_的指针 - 或者你只是没有尝试编译它。 – Armali

0

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]) 
{ 
    ... 
} 
+0

虽然答案的主要部分是正确的,但最后一块不是;该函数相当于'void fun(char(* a)[10])'或'void fun(char a [] [10])'。 – Armali

0
void fill(struct box**, int, int, char*); 

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

因此,原型

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

几乎是正确的,除了可以省略仅主(第一)的矩阵声明的维数,因此,我们需要至少指定width在其中,这方便也传递给函数,只有参数顺序已被改变,使得width定义足够早:

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

main函数调用因此是:

fill(length, width, soup, alphabet);