Can you return an array of structs in a function? I'm supposed to make a linked list where the node contains an array of structs. I'm using a grocery list thing as my array of structs.

struct grocery{
char *name;
float price;
};

struct node{
struct grocery list[5];   //no idea how to make this flexible, either
struct node *next;
};

could you write a function such as this?

struct grocery[] get_data(struct node n)
{
}

Ive tried that as well as grocery[5] as the return type

is there a way to return an array of structs? also, in my definition of a node, is there a way to make the grocery field a flexible array?

Thanks alot

Recommended Answers

All 2 Replies

You could return the address to the array of structures

yes u can declare such function.

But i would suggest u to declare your node as


struct node{
struct grocery* list;
struct node *next;
};

u can allocate memory to it dynamically as

node x;
x.list = (struct grocery *)malloc(5*sizeof(struct grocery));

and u can access them as
*(x.list) ( equiv to x.list[0])
*(x.list + 1) ( equiv to x.list[1])
etc.......

and u can change the syntax of your function as

struct grocery* get_data(struct node n)
{
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.