指標變數傳遞給函數

來源:互聯網
上載者:User

  大家都知道,指標變數儲存的地址,但是,在進行函數調用的時候,大家有想過能否將指標變數本身傳遞給一個函數了?

這裡首先給大家糾正一個錯誤,其實main函數內部聲明的變數也是局部變數,它們也只是在main函數內部有效,只不過是它們的生命週期和全域變數一樣長而已。全域變數一定是定義在函數外部的。

  好了,現在大家知道了--------無法把指標變數本身傳遞給一個函數。測試一下:

#include <stdlib.h>#include <stdlib.h>#include <string.h>void allocate_mem(char *p, int n){p = (char *)malloc(n * sizeof(char));}int main(void){char *dst = NULL;allocate_mem(dst, 20);strcpy(dst, "I love Linux");free(dst);return 0;}

  經測試,單步調試執行到strcpy函數時出現:No source available for "memcpy() at 0x5263f46" (以上測試在Fedora9 eclipse環境下)。觀察得到dst的值仍然為NULL,說明malloc函數動態分配的記憶體沒有賦給dst,而是賦給了dst一個備份,而這個備份是隨編譯器自動分配和回收的,當allocate_mem函數調用結束,這個備份也就被釋放。


那麼怎樣獲得一塊記憶體區了?

1、用指標函數實現

#include <stdlib.h>#include <string.h>#include <stdio.h>char *allocate_mem(char *p, int n){p = (char *)malloc(n * sizeof(char));return p;}int main(void){char *dst = NULL;dst = allocate_mem(dst, 20);strcpy(dst, "I love Linux");free(dst);return 0;}

2、用二級指標實現

#include <stdlib.h>#include <string.h>#include <stdio.h>void allocate_mem(char **p, int n){*p = (char *)malloc(n * sizeof(char));}int main(void){char *dst = NULL;allocate_mem(&dst, 20);strcpy(dst, "I love Linux");free(dst);return 0;}

  這裡很顯然,參數是&dst,而不是dst指標變數,這樣傳遞是地址,而非dst變數本身。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.