user081608
user081608

Reputation: 1113

Returning a struct from a function

I have a function in which puts data into a struct. My struct looks like this:

 typedef struct vertex_tag{
    int visited;
    double weight;
    int prev;
 }vertex_t;

I initialize it like this;

vertex_t * vertex[G->vertices];
    for(i=0; i < G->vertices; i++)
    {
        vertex[i] = (vertex_t*)malloc(sizeof(vertex_t));
        vertex[i]->weight = FLT_MAX;
        vertex[i]->visited = 0;
    }

It goes through the function putting data into the array, weight, visited and prev.

My question is, how do I get those values in my main function? Would I create another

vertex * vertex[]

In my main then set it equal to what I return?

Any thoughts?

Upvotes: 0

Views: 92

Answers (2)

Maxime Ch&#233;ramy
Maxime Ch&#233;ramy

Reputation: 18831

Allocating on the heap:

You should use malloc to create your array. Otherwise, you create the array on the stack and you can't return it. If you return the address of your array, the data may be corrupted.

Replace:

vertex_t * vertex[G->vertices];

to

vertex_t ** vertex = malloc(sizeof(vertex_t*) * G->vertices);

And return vertex which is of type vertex_t **.

An array of vertex_t instead of an array of pointers:

Also, it is not the question but I'm wondering why are you using an array of pointers. You could change your code like that:

vertex_t * vertex = malloc(sizeof(vertex_t) * G->vertices);
for(i=0; i < G->vertices; i++)
{
    vertex[i].weight = FLT_MAX;
    vertex[i].visited = 0;
}

And return vertex, of type vertex_t * (an array of vertex_t). If you need the address of an element in that array, you can still do &vertex[i].

Both approaches would work but in your solution, you do extra memory allocations which use more memory, it's slower and you'll need to free that memory at some point. At a hardware point of view, you'll also do more cache misses leading to a slower code if you frequently iterate over all the array.

The only usage would be if you have vertices created by another function and you don't want to copy the data in your array.

I'd suggest you to draw the 2 solutions: one is an array with big cells and the other is an array with pointers to individual cells.

Upvotes: 2

user1814023
user1814023

Reputation:

Since vertex is an array, you can not return an array from a function. Either you have to...

1. return the pointer to the array from the function 
or
2. Put the `vertex` array in a structure and return the structure.

Upvotes: 0

Related Questions