[英]Can a single pointer be initialized in a function and if so how?
我得到了这个函数原型void create_smth(smth* s)
并且要求这个函数创建、初始化并返回一个 smth 变量。 这甚至可能吗? 据我所知,我需要一个双指针来做这样的事情。 我在这个函数中做的是
s=(smth*)malloc(sizeof(smth));
这大概是错误。
在我的主要我已经尝试过
smth* smth1=NULL;
create_smth(smth1);
和
smth smth1;
create_smth(&smth1);
但我的代码一直崩溃(分段错误;核心转储)。 我开始怀疑这是否是教练的错误,但直接问他很愚蠢,但练习需要我上面所说的。 谢谢大家。
对我来说看起来像是导师的错误。 您是正确的, void create_smth(smth* s)
原型无法返回值,无论是传统的return
意义(它是void
),还是使用双指针。 只有两种方法可以做到这一点:
smth* creat_smth()
{
smth* mySmth = malloc(sizeof *mySmth);
// check malloc return valid pointer, initialize fields with mySmth->
return mySmth;
}
int main(void)
{
smth* smth1 = creat_smth();
...
return 0;
}
或者
void creat_smth(smth** mySmth)
{
*mySmth = malloc(sizeof **mySmth);
// check malloc returned valid pointer, initialize fields with (*mySmth)->
}
int main(void)
{
smit* smth1;
creat_smth(&smth1);
...
return 0;
}
值得向您的导师寻求澄清。 也就是说,遵循int init_smth(smth *x)
模式的函数至少在某种程度上是常见的——但请注意名称:此类函数通常称为init_•
,而不是create_•
(因为它不会为此创建存储对象,它只是填充它)。
当预计堆栈分配结构是正确的事情时,这是有道理的。 用户将传递一个指向本地分配结构的指针,而不是使用malloc
:
smth my_smth;
init_smth(&my_smth);
并且在init_smth
内部会init_smth
一些中等复杂的初始化(但同样没有malloc
:对象的内存已经分配)。
然而,即使如此,函数返回指示成功的状态代码也更为常见(因此在我的原型中返回类型为int
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.