Returns an array of structures or an array of pointers to a structure?

If you need to return a struct from a function, you usually return a pointer to a struct .

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

  • returns an array of structures (pointer to the first element)
  • or return an array of pointers to a structure?

I drew a diagram for the following two options:

one

enter image description here

2:

enter image description here

Given the following definition of structure

 struct values { int a; int b; }; 

Here is an example code for accessing the structure fields of two parameters:

Option number 1:

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

Option number 2:

  struct values **vals = get_values2(); printf("%d, %d\n", values[0]->a, values[1]->b); 
+8
c arrays pointers struct
source share
4 answers

The only problem that I see not to use version 1 is that it would be easier to identify the number of structures (returned) in the second version, since the NULL pointer can be used as a stop disk element, whereas in the first version it was it would be impossible to define a freeze frame element.

+6
source share

If you have no reason to return a pointer to pointers (for example, if you want to change the pointers themselves later), I think the pointer to the structure is good enough. No need to cheat with double pointers.

+5
source share

As an example for a C beginner’s book, the question will undoubtedly be better satisfied with option 1 (without indirection), as mentioned in the answers so far. If there is still a question for the question (for example, which is the best way to convey structures in a large structure), then I would certainly go for option 2. Why? Structures are complex data units and, as a rule, become autonomous objects that are distributed and transmitted and placed in different ways - all the code that processes them with direct access needs to be rewritten if the processing of data becomes more complicated.

+1
source share

For me, as the number of instructions increases, the complexity of the code increases even faster. Therefore, I prefer your option # 1: struct values *foo() .

If the data requirements are approaching # 2: struct values **foo() , suggest creating a new typedef struct values *ValuesSet type typedef struct values *ValuesSet and return a pointer to this: ValuesSet *foo() .

0
source share

All Articles