How do you return a structure from an array inside a function? (pointers)

Consider this code:

typedef struct fruits_s { char* key; char value; } fruits_t; static fruits_t fruit_array[] = { { "Apple", 1 }, { "Banana", 2 }, { "Grape", 3 }, { "Orange", 4 } }; static fruits_t* getFruitFromValue(char value) { int i; for (i = 0; i < sizeof(fruit_array)/sizeof(fruit_array[0]); i++){ if (value == fruit_array[i].value){ return fruit_array[i]; } } } 

I am new to C and I am still involved when pointers are needed / used. I am spoiled from Java background. So, in the above code, what confuses me is, should the function return the fruits_t* pointer? Or something different? When I do fruit_array[i] , is it a pointer to my structure or to my own structure?

As they say, later in my code, when I want to use this function, it is:

  fruits_t* temp = getFruitFromValue(1); 

or

  fruits_t temp = getFruitFromValue(1); 

or

  fruits_t temp = &getFruitFromValue(1); 
+4
source share
1 answer

The function can return either - your choice. You said you would return a pointer; that ok while you do it.

When you write:

 static fruits_t *getFruitFromValue(char value) { int i; for (i = 0; i < sizeof(fruit_array)/sizeof(fruit_array[0]); i++){ if (value == fruit_array[i].value){ return fruit_array[i]; } } } 

There are several problems:

  • fruit_array[i] is a structure, not a pointer. Use return &fruit_array[i]; .
  • If the loop exits, you are not returning a value from the function at all.

Fixing these lines results in:

 static fruits_t *getFruitFromValue(char value) { int i; for (i = 0; i < sizeof(fruit_array)/sizeof(fruit_array[0]); i++) { if (value == fruit_array[i].value) return &fruit_array[i]; } return NULL; } 

This is normal because the returned pointer is static data that will enliven this function. If you try to return a pointer to non-static data, you (probably) have an error on your hands, if you have not used dynamic memory allocation (via malloc() , etc.).

You can also return the structure; error return processing becomes more complicated. If you have C99, you can use the "compound literal":

 static fruits_t getFruitFromValue(char value) { int i; for (i = 0; i < sizeof(fruit_array)/sizeof(fruit_array[0]); i++) { if (value == fruit_array[i].value) return fruit_array[i]; } return (fruits_t){ .key = "", .value = 0 }; } 
+4
source

Source: https://habr.com/ru/post/1447116/


All Articles