c語言指標做函式引數,使用指標地址(二級指標)在被調函式中修改主調函式的指標。
阿新 • • 發佈:2019-02-09
1.程式碼
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char *prive; int data; } T_Str; void copy_mem( char *dst) { strcpy(dst, "aa"); } void copy_remalloc(char *dst){ dst=strdup("aaa"); } void copy_remalloc_by_pointer(char **dst){ *dst=strdup("aaa"); } void dump_str(T_Str str){ printf("----------->\n"); printf("str.data:=%d \n", str.data); if(str.prive){ printf("str.prive:=%s \n", str.prive); }else{ printf("str.prive has no data \n"); } printf("<-----------\n"); } #define PRIVE_SIZE 16 void test(){ T_Str str; memset(&str, 0, sizeof(T_Str)); str.prive=NULL; str.prive=(char *)malloc(sizeof(char)*PRIVE_SIZE); copy_mem(str.prive); dump_str(str); memset(&str, 0, sizeof(T_Str)); str.prive=NULL; copy_remalloc(str.prive); dump_str(str); memset(&str, 0, sizeof(T_Str)); str.prive=NULL; copy_remalloc_by_pointer(&str.prive); dump_str(str); } int main(int argc, char *argv[]) { test(); return 0; }
2.執行結果
----------->
str.data:=0
str.prive:=aa
<-----------
----------->
str.data:=0
str.prive has no data
<-----------
----------->
str.data:=0
str.prive:=aaa
<-----------
3.總結
其實很簡單,要想給一個指標重新賦值,使它指向新的記憶體並修改,傳入地址即可。和普通的二級指標一樣,結構體同樣符合c的規範。