簡體   English   中英

可以在函數中初始化單個指針嗎?如果可以,如何初始化?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM