passing array of structure pointer to a function

c, pointers, struct

Solution

The type of `&vertices` in the call `create_vertices(&vertices, 20)` is not what you think.

It is a pointer to an array of pointers to structs:

struct node *(*)[20]

and not

struct node **

Drop the `&` in the call and you'd be back in business.

The compilation (using GCC 4.7.0 on Mac OS X 10.7.4):

$ 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]’
$

The code:

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

Drop the `&` and the code compiles cleanly.

Problem

I am writing a program in which I have to pass an array of structure pointers to a function in main body as follows ``` struct node *vertices[20]; create_vertices (&vertices,20); ``` implementation of function is some thing like this ``` void create_vertices (struct node *vertices[20],int index) { } ``` in this I have to pass an array of structure pointers with index 20, the declaration I did outside mains is as follows I ``` void create_vertices(struct node **,int); ``` However each time compiling the code gives me problem in these three lines only as ``` 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 *’ ``` I am unable to understand how should I be doing this. What I want to be able to do is: - Declare an array of structure pointers in main (which I already did). - Pass the address of array to function (here is where I goofed up). - Declare the correct prototype of function outside mains. The code has to be on C and I am testing it on Linux. Can some one point me?

Original source