Change a pointer

来源:互联网 发布:网络博客行业 编辑:程序博客网 时间:2024/06/06 16:43
If you want to change  something that's pass in as a parameter,you have to pass in a pointer to whatever you want to change. If it's a pointer,then you need to pass in a pointer to pointer(maybe someone will call it "double pointer ").

Now i’ll show you guys a case:

#include<malloc.h>#include<stdio.h>#include<stdlib.h>#include<string.h>void getmemory(char *p){    p=(char*)malloc(100);    strcpy(p,"hello world");}int main(){    char *str = NULL;    getmemory(str);    printf("%s\n",str);    free(str);    return 0;}

this code can be compiled successfully,run it, it get corruption.
So how can I get this code to work? Here is the solution.

#include<malloc.h>#include<stdio.h>#include<stdlib.h>#include<string.h>void getmemory(char **p){    *p=(char*)malloc(100);    strcpy(*p,"hello world");}int main(){    char *str = NULL;    getmemory(&str);    printf("%s\n",str);    free(str);    return 0;}

And its output:
hello world

原创粉丝点击