C語言、指標的指標和野指標的問題

來源:互聯網
上載者:User

int _tmain(int argc, _TCHAR* argv[])
{  

   int * p = (int *) malloc(sizeof(int));
   //*p = 10;
   flee(p);
   printf("%d",*p);
   //釋放p
   free(p);
   printf("----");

   int * i = (int *) malloc(sizeof(int));
   flee2(&i);
   //釋放i
   printf("%d",*i);
   free(i);
}

//入參為指標,仍為值傳遞,即副本。只有引用傳遞是傳遞p本身。
void flee(int *q)
{
  //副本修改的是指標所指變數的值,而不是指標本身。
  *q = 20;
  //出棧時副本被自動銷毀,而外面的P所指變數的值被改了,但指標地址實際上未改變。
}

void flee2(int **q)
{
  //int i = 5;
  ////副本指向了一個新的位置,所以真正地修改了一個指標地址。但產生的一個問題是,原始定義的i產生了野指標。
  //*q = &i;
  //i =3;
if(q != NULL && *q != NULL)
{
 *(*q) = 5;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.