简体   繁体   English

可以在函数中初始化单个指针吗?如果可以,如何初始化?

[英]Can a single pointer be initialized in a function and if so how?

I have been given this function prototype void create_smth(smth* s) and it is asked that this function creates, initializes and returns a smth variable.我得到了这个函数原型void create_smth(smth* s)并且要求这个函数创建、初始化并返回一个 smth 变量。 Is this even possible?这甚至可能吗? To my knowledge I would need a double pointer to do such a thing.据我所知,我需要一个双指针来做这样的事情。 What I am doing in this function is我在这个函数中做的是

s=(smth*)malloc(sizeof(smth));

This is probably the mistake.这大概是错误。

In my main I have tried在我的主要我已经尝试过

smth* smth1=NULL;
create_smth(smth1);

and

smth smth1;
create_smth(&smth1);

but my code keeps crashing (Segmentation fault; core dump).但我的代码一直崩溃(分段错误;核心转储)。 I am starting to wonder if it is an instructors mistake but feel stupid to ask him straight up but the excercise requires what I stated above.我开始怀疑这是否是教练的错误,但直接问他很愚蠢,但练习需要我上面所说的。 Thanks everyone.谢谢大家。

Looks like instructor's mistake to me.对我来说看起来像是导师的错误。 You are correct that the void create_smth(smth* s) prototype cannot return a value, either in the traditional return sense (it is void ), or using a double pointer.您是正确的, void create_smth(smth* s)原型无法返回值,无论是传统的return意义(它是void ),还是使用双指针。 The only two ways to do this:只有两种方法可以做到这一点:

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;
}

or或者

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;
}

It's worth asking your instructor for clarification.值得向您的导师寻求澄清。 That said, it's at least somewhat common to have functions that follow the pattern int init_smth(smth *x) — but note the name: such functions are usually called init_• , not create_• (because it doesn't create the storage for this object, it just fills it).也就是说,遵循int init_smth(smth *x)模式的函数至少在某种程度上是常见的——但请注意名称:此类函数通常称为init_• ,而不是create_• (因为它不会为此创建存储对象,它只是填充它)。

This makes sense when it's expected that stack-allocating the struct is the right thing to do.当预计堆栈分配结构是正确的事情时,这是有道理的。 Instead of using malloc , the user would pass a pointer to a locally allocated structure:用户将传递一个指向本地分配结构的指针,而不是使用malloc

smth my_smth;
init_smth(&my_smth);

And inside init_smth some moderately complex initialisation would take place (but again without malloc : the memory for the object is already allocated).并且在init_smth内部会init_smth一些中等复杂的初始化(但同样没有malloc :对象的内存已经分配)。

However, even then it's more common for the function to return a status code indicating success (hence the return type int in my prototype above).然而,即使如此,函数返回指示成功的状态代码也更为常见(因此在我的原型中返回类型为int )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM