C语言二重指针传参数

错误案例:

void Getmemery(char *p)
{
    p=(char *)malloc(100);
}

void main()
{
    char *str=NULL;

    Getmemery(str);
    strcpy(str,"hello world");
    printf("%s",str);
    free(str);
}

错误原因:

char* p传递的是参数拷贝,不要指望可以通过char*p进行参数传递

改正方法一:

char *Getmemery(void)
{
    char *p=(char *)malloc(100);

    return p;
}

void main()
{
    char *str=NULL;

    str = Getmemery();
    strcpy(str,"hello world");
    printf("%s",str);
    free(str);
}

改正方法二:

void Getmemery(void **p)
{
    *p=(void **)malloc(100);
}

void main()
{
    char *str=NULL;

    Getmemery(&str);
    strcpy(str,"hello world");
    printf("%s",str);
    free(str);
}

操作案例一:

void testm(char** a)//传递指针地址,这样才能将指针传递进来,即将主函数中参数的地址传递进来

{

    *a = (char**)calloc(1,sizeof(char)); //*a就是将指针的内容赋值,付给他一个地址

    **a = 'i';//指针所指向的地址的内容

}

 

int main(int argc, const char * argv[]) {

    // insert code here...

    char* a = NULL;

    testm(&a);

    printf("a1----%s-----\n",a);

    printf("Hello, World!\n");

    return 0;

}

 操作案例二:

void testm(char** a)

{   

   char* b = (char*)calloc(1,sizeof(char));

    *b = 'k';

    *a = &(*b);//先取指针b的内容,即指针b所指向的内容的地址,再取内容的地址,让指针a指向

}

int main(int argc, const char * argv[]) {

    // insert code here...

    char* a = NULL;

    testm(&a);

    printf("a1----%s-----\n",a);

    printf("Hello, World!\n");

    return 0;

}

posted @ 2014-11-26 11:14  凤凰连城  阅读(1096)  评论(0编辑  收藏  举报