大家都知道,指針變量存儲的地址,但是,在進行函數調用的時候,大家有想過能否將指針變量本身傳遞給一個函數了?
這裏首先給大家糾正一個錯誤,其實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變量本身。