gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:08:39 24 4
gpt4 key购买 nike

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

     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. 在主电源外声明正确的函数原型(prototype)。

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

最佳答案

调用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);
}

删除 & 代码编译干净。

关于c - 将结构指针数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10845645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com