返回结构指针 [英] Returning a struct pointer

查看:19
本文介绍了返回结构指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下结构和函数返回一个指针:

Suppose I have the following struct and function returning a pointer:

typedef struct {
  int num;
  void *nums;
  int size;
} Mystruct;

Mystruct *mystruct(int num, int size)
{ 
   //Is the following correct? Is there a more efficient way?
   Mystruct mystruct;
   mystruct.num = num;
   mystruct.size = size;
   mystruct.nums = malloc(num*sizeof(size));
   Mystruct *my;
   *my = mystruct;
   return my;
}

我想使用上述函数定义任何 Mystruct 指针.我是应该声明一个Mystruct变量,定义Mystruct的属性,给它赋值一个指针,然后返回指针还是立即通过一个指针定义一个mystruct属性的属性?

I want to define any Mystruct pointer using the above function. Should I declare a Mystruct variable, define the properties of Mystruct, assign a pointer to it, and return the pointer or define the properties of a mystruct property through a pointer immediately?

推荐答案

我是否应该声明一个 Mystruct 变量,定义 Mystruct 的属性,为其分配一个指针,并返回指针

Should I declare a Mystruct variable, define the properties of Mystruct, assign a pointer to it, and return the pointer

绝对不会,因为函数中定义的变量(在auto"存储类中)将随着函数退出而消失,并且您将返回一个悬空指针.

Definitely not, because the variable defined in the function (in "auto" storage class) will disappear as the function exits, and you'll return a dangling pointer.

你可以接受一个指向Mystruct的指针(调用者有责任分配它)并填写它;或者,您可以使用 malloc 来创建一个新的(调用者有责任在完成后释放它).第二个选项至少可以让你保留你似乎热衷的函数签名:

You could accept a pointer to a Mystruct (caller's responsibility to allocate that) and fill it in; or, you can use malloc to create a new one (caller's responsibility to free it when it's done). The second option at least lets you keep the function signature you seem to be keen on:

Mystruct *mystruct(int num, int size)
{
   Mystruct *p = malloc(sizeof(MyStruct));
   ....
   return p;
}

但它通常是次等的——因为调用者无论如何都必须承担责任,不妨采用第一个选项并可能获得性能(如果调用者可以使用自动类实例,因为它知道使用范围有界).

but it's often an inferior one -- since the caller has to have responsibilities anyway, may as well go with the first option and potentially gain performance (if the caller can use an auto-class instance because it knows the scope of use is bounded).

这篇关于返回结构指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆