将结构指针数组传递给函数

Reg*_*ser 4 c struct pointers

我正在编写一个程序,其中我必须将结构指针数组传递给主体中的函数,如下所示

     struct node *vertices[20];
create_vertices (&vertices,20);
Run Code Online (Sandbox Code Playgroud)

函数的实现是这样的

void create_vertices (struct node *vertices[20],int index)
{
}
Run Code Online (Sandbox Code Playgroud)

在此我必须传递一个索引为 20 的结构指针数组,我在 mains 之外所做的声明如下我

void create_vertices(struct node **,int);
Run Code Online (Sandbox Code Playgroud)

然而,每次编译代码时,这三行都给我带来了问题

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 *’
Run Code Online (Sandbox Code Playgroud)

我无法理解我该怎么做。我希望能够做的是:

  1. 在 main 中声明一个结构指针数组(我已经这样做了)。
  2. 将数组的地址传递给函数(这是我搞砸的地方)。
  3. 在电源外声明正确的函数原型。

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

Jon*_*ler 5

&vertices通话中的类型create_vertices(&vertices, 20)不是您想的那样。

它是一个指向结构指针数组的指针:

struct node *(*)[20]
Run Code Online (Sandbox Code Playgroud)

并不是

struct node **
Run Code Online (Sandbox Code Playgroud)

挂断&电话,您将重新开始营业。

编译(在 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]’
$
Run Code Online (Sandbox Code Playgroud)

编码:

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);
}
Run Code Online (Sandbox Code Playgroud)

删除&并且代码编译干净。