[英]How do you return a struct from an array within 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 am still learning when pointers are necessary/used. 我是C的新手,并且在需要/使用指针时仍在学习。 I come spoiled from a Java background. 我从Java背景中被宠坏了。 So, in the above code, what I'm confused of is should the function return a pointer fruits_t*
? 那么,在上面的代码中,我感到困惑的是函数应该返回指针 fruits_t*
? Or something else? 或者是其他东西? When I do fruit_array[i]
is that a pointer to my struct, or the struct itself? 当我做fruit_array[i]
是指向我的结构或结构本身的指针?
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);
The function could return either — your choice. 该功能可以返回 - 您的选择。 You've said you'll return a pointer; 你说你会回指针; that's OK as long as you do. 只要你这样做就没问题。
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. fruit_array[i]
是一个结构,而不是指针。 Use return &fruit_array[i];
使用return &fruit_array[i];
. 。 Fixing those leads to: 修复这些导致:
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 OK because the pointer you return is to static data that will outlive the function. 这是可以的,因为您返回的指针是静态数据,该数据将比该函数更长。 If you tried to return a pointer to non-static data, you would (probably) have a bug on your hands, unless you used dynamic memory allocation (via malloc()
et al). 如果您尝试返回指向非静态数据的指针,除非您使用动态内存分配(通过malloc()
等),否则您可能(可能)手上有一个错误。
You could also return the structure; 你也可以归还结构; handling the error return becomes harder. 处理错误返回变得更难。 If you've got C99, you can use a 'compound literal': 如果你有C99,你可以使用'复合文字':
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 };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.