【发布时间】:2011-02-11 18:35:41
【问题描述】:
假设我有以下结构和函数返回一个指针:
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 属性的属性?
【问题讨论】:
-
也许您可以编写这两个选项。从描述中,不清楚您的意图是什么。
-
记住......永远不要将指针“从堆栈”向上传播。