2012-06-01 55 views
3

我写一个程序,其中我不得不结构指针数组传递给一个函数在主体如下传递结构指针的数组的函数

 struct node *vertices[20]; 
create_vertices (&vertices,20); 

执行功能是这样一些事

void create_vertices (struct node *vertices[20],int index) 
{ 
} 
在此

我要通过结构的指针数组与索引20, 声明我没有外部电源被如下我

void create_vertices(struct node **,int); 

但是每次编译代码给了我问题,这三条线仅作为

bfs.c:26:6: error: conflicting types for ‘create_vertices’ 
bfs.c:8:6: note: previous declaration of ‘create_vertices’ was here 
bfs.c: In function ‘create_vertices’: 
bfs.c:36:15: error: incompatible types when assigning to type ‘struct node’ from type ‘struct node *’ 

我无法理解我应该怎么做这个。 我想要做的是:

  1. 声明main(我已经做过)中的结构指针数组。
  2. 将数组的地址传递给函数(这里是我疯狂的地方)。
  3. 声明市电外功能的正确原型。

代码必须在C上,我正在Linux上测试它。 有人可以指点我吗?

回答

4

呼叫create_vertices(&vertices, 20)中的&vertices的类型不是你所想的。

这是一个指向指针数组结构:

struct node *(*)[20] 

,而不是

struct node ** 

&呼叫,你会回来的业务。

汇编(在Mac OS X 10.7.4使用GCC 4.7.0):

$ gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes -c x3.c 
x3.c: In function ‘func1’: 
x3.c:16:9: warning: passing argument 1 of ‘create_vertices’ from incompatible pointer type [enabled by default] 
x3.c:7:10: note: expected ‘struct node **’ but argument is of type ‘struct node * (*)[20]’ 
$ 

代码:

struct node { void *data; void *next; }; 

void make_node(struct node *item); 
void func1(void); 
void create_vertices(struct node **array, int arrsize); 

void create_vertices(struct node *vertices[20], int index) 
{ 
    for (int i = 0; i < index; i++) 
     make_node(vertices[i]); 
} 

void func1(void) 
{ 
    struct node *vertices[20]; 
    create_vertices(&vertices, 20); 
} 

&和代码完全编译。

2

正如你所写:struct node *vertices[20];声明了一个指向节点的指针数组。现在,如果你想创建一个改变其元素的功能,你应该声明一个函数,这个类型的数组作为参数:

void create_vertices(struct node *arr[20], int size) 

或者因为大小可以在这种情况下中省略,这是更好地申报它为:

void create_vertices(struct node *arr[], int size) 

注意,这个函数可以调用这样的:create_vertices(vertices, 20);这使得该函数(arr)的第一个参数为指向该数组的第一个元素。您可以在此功能中更改此数组,并且更改将在外部可见。

比方说你有改变node的功能void foo(struct node *ptr)ptr指向。当您声明struct node *ptr;并传递给此函数:foo(ptr);时,它可以更改此node对象,并且更改在外部可见,但它不能更改传递的指针ptr本身。当你需要改变函数内的指针,以便外部可见更改时,就是当你将指针的地址传递给指向指针的函数时的情况。

+0

很好的解释+1对于上面的某个人写代码,因此接受他的答案。 –

0

create_vertices的原型中,第一个参数是一个指向结构指针的指针。在定义中,第一个参数是20个指向结构指针的数组。

原型和定义都必须相同。