Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return an array of structs or an array of struct pointers?

If you need to return a struct from a function, you would normally return a pointer to the struct instead.

If you then want to return an array of structs, is it recommended to:

  1. return an array of structures (pointer to the first element)
  2. or return an array of struct pointers?

I have drawn a diagram for the two options below:

1:

enter image description here

2:

enter image description here

Given the following struct definition

struct values {
    int a;
    int b;
};

here is some sample code for accessing the fields of the structs from the two options:

Option #1:

 struct values *vals = get_values1();
 printf("%d, %d\n", values[0].a, values[1].b);

Option #2:

 struct values **vals = get_values2();
 printf("%d, %d\n", values[0]->a, values[1]->b);
like image 360
Tyilo Avatar asked Aug 01 '13 11:08

Tyilo


People also ask

Can you return an array of structs in C?

It is not possible to return an array, unless the array itself is a member of a structure which is being returned.

Can you return a struct pointer in C?

Use Standard Notation to Return struct From Function Now, functions in C can return the struct similar to the built-in data types. In the following example code, we implemented a clearMyStruct function that takes a pointer to the MyStruct object and returns the same object by value.

Can you create an array of pointers to structures?

It is not possible to create an array of pointer to structures.


1 Answers

The only issue I see to not use version 1, is that it might be easier to identify the number of structures (returned) in the second version, as a NULL pointer can be used as a stopper element, whereas in the first version it might not be possible to define a stopper element.

like image 108
alk Avatar answered Oct 15 '22 22:10

alk