pointer to pointer

首先讨论一下一级指针的问题,普通的链表问题就不再赘述了,但是如果要对指针申请动态内存,在某个函数内部是没办法实现的,实参和形参的基本概念

[codesyntax lang=”cpp”]

void getmemory(char *p, int num){
     ip=(char*)malloc(sizeof(char)* num);
}
 
void test(){
     char *str=null;
     getmemory(str,100);  // actually the address of str is not redefined, instead some memory is overflowed here
     strcpy(str,"hello");
}

[/codesyntax]

这是一个典型的错误,为了解决这个问题就需要二级指针了

[codesyntax lang=”cpp”]

void getmemory(char **p, int num){
     *p=(char*)malloc(sizeof(char)*num);
}
 
void test(){
     char *str = NULL;
     getmemory(&str, 100); // 注意参数是 &str,而不是str
     strcpy(str, "hello");
     std::cout<< str << std::endl;
     free(str);

}

[/codesyntax]

前些日子做一个online test的时候碰到了一个删除链表具有某个特定值的节点,函数如下

[codesyntax lang=”cpp”]

void remove(linklist **head, int target){

}

[/codesyntax]

开始的时候不太明白为什么要用二级指针,但是现在明白了,如果head的值就是target,这个函数就需要修改head的指向,所以需要用二级指针。
一级指针也有方法处理,但是函数的返回值就不能是void了

Leave a Reply

Your email address will not be published. Required fields are marked *