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 am still learning when pointers are necessary/used. I come spoiled from a Java background. So, in the above code, what I'm confused of is should the function return a pointer fruits_t*? Or something else? When I do fruit_array[i] is that a pointer to my struct, or the struct itself?
That being said, later in my code when I want to use the function, is it this:
fruits_t* temp = getFruitFromValue(1);
or
fruits_t temp = getFruitFromValue(1);
or
fruits_t temp = &getFruitFromValue(1);
fruit_array[i]is the struct, if you want to return a pointer to it,&fruit_array[i]or, equivalently,(fruit_array + i).getFruitFromValue()asstaticwhen you to return a static array element.staticmay be so that it is not visible outside the source file; I would assume that was why. I grant you there could be confusion about it, but it's not clear that there is confusion about it.