c语言--二级指针在函数间的传递和使用

来源:互联网 发布:中信证券 for mac 编辑:程序博客网 时间:2024/05/21 21:37
#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct{    int index;    char **my_data;}Test_Stru;typedef struct{    int index;    Test_Stru **test;}Father_Stru;void dump_test_stru(Test_Stru *test){    if(!test){        printf(" dump structure is null \n ");        return;    }    printf("-------------->\n");    printf("test index:= %d \n", test->index);    if(*test->my_data){        printf("test value:= %s \n ", *test->my_data);       }    printf("<--------------\n");    return;}void dump_test_stru_father(Father_Stru *f){    if(!f){        printf("your stru is null \n");    }    printf("------->\n");    printf("f->index:= %d \n", f->index);    if(*f->test){        dump_test_stru(*f->test);    }    printf("<-------\n");}Test_Stru *test_second_rank_pointer(){    Test_Stru *test = (Test_Stru *)malloc(sizeof(Test_Stru));    memset(test, 0, sizeof(Test_Stru));    test->index=1;    test->my_data=(char **)malloc(sizeof(char **));    *test->my_data = strdup("hello world");    return test;}Father_Stru *test_struct_call(Test_Stru *test){    Father_Stru *father;    father = (Father_Stru *)malloc(sizeof(Father_Stru));    memset(father, 0, sizeof(Father_Stru));    father->index=0;#if 0        //c的世界是个很有意思的世界。        //当我们在被调函数中创建一个指针来接收参数,        //它实际上可以看成原指针的一个副本,它的性质和原指针一样,是一个指针,而且和原指针指向同一个内存区域。        //因为是被调函数中创建的,所以它的生命周期和所在函数相同,当函数返回时,也就被清空了。        //所以,如果我们想保存数据给我们新创建的全局变量时,要把指针的值赋给新的变量,        //而不能把把指针的地址赋给变量,因为这个指针只是一个副本,一旦函数返回,它存储的信息就会被释放。    father->test =(Test_Stru **) malloc(sizeof(Test_Stru **));    father->test=&test;#else    father->test =(Test_Stru **) malloc(sizeof(Test_Stru **));    *father->test=test;#endif        if(*father->test){        printf("This is my struct call, test->index:= %d \n", (*father->test)->index);        printf("This is my struct call, value is: %s \n ", *(*father->test)->my_data );    }    return father;}Father_Stru *test_struct_call2(Test_Stru **test){    Father_Stru *father;    father = (Father_Stru *)malloc(sizeof(Father_Stru));    memset(father, 0, sizeof(Father_Stru));    father->index=0;    father->test=test;        return father;}int main(int argc, char* argv[]){    printf("prepare test fo make father stru------------------> \n");    Test_Stru *test=test_second_rank_pointer();    dump_test_stru(test);    printf("<---------------------\n\n");    printf("f1 stru make ====================>\n");    Father_Stru *f1 = test_struct_call(test);    dump_test_stru_father(f1);    printf("<=================================\n\n");        printf("f2 stru make ====================>\n");    Father_Stru *f2 = test_struct_call2(&test);    dump_test_stru_father(f2);    printf("<=================================\n\n");    return 0;}