返回一个指针结构 [英] Returning a struct pointer
问题描述
假设我有下面的结构和函数返回一个指针:
typedef结构{
INT NUM;
无效* NUMS;
INT大小;
} MYSTRUCT;MYSTRUCT * MYSTRUCT(INT NUM,INT大小)
{
//是下面的正确吗?有没有更有效的方法?
MYSTRUCT MYSTRUCT;
mystruct.num = NUM;
mystruct.size =大小;
mystruct.nums =的malloc(NUM *的sizeof(大小));
MYSTRUCT *我的;
*我= MYSTRUCT;
返回我的;
}
我想用上面的函数定义任何MYSTRUCT指针。我要声明一个变量MYSTRUCT,定义MYSTRUCT的属性,指针分配给它,并返回指针或通过指针定义MYSTRUCT财产的属性立刻?
我应该声明一个变量MYSTRUCT,
限定MYSTRUCT的属性,
一个指针分配给它,并返回
指针
块引用>肯定不是,因为变量在函数中定义(在自动存储类)将消失函数退出,你会返回一个悬摆指针。
您可以的接受的一个指针
MYSTRUCT
(主叫方的责任来分配),并填写好;或者,你可以使用的malloc
以创建一个新的(调用者负责释放它,当它完成)。第二个选项,至少可以让你保持函数签名,你似乎热衷于:MYSTRUCT * MYSTRUCT(INT NUM,INT大小)
{
MYSTRUCT * P =的malloc(sizeof的(MYSTRUCT));
....
回磷;
}但通常较差的一 - 因为调用者必须有责任,无论如何,可以与第一选择还是去和可能获得的性能(如,因为它知道使用范围的调用者可以使用自动类实例为界)。
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; }
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?
解决方案Should I declare a Mystruct variable, define the properties of Mystruct, assign a pointer to it, and return the pointer
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.
You could accept a pointer to a
Mystruct
(caller's responsibility to allocate that) and fill it in; or, you can usemalloc
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屋!