指针传递

来源:互联网 发布:绿色上网软件手机软件 编辑:程序博客网 时间:2024/06/06 03:17

错误程序--程序崩溃:

#include <stdlib.h>#include <string.h>#include <stdio.h>void GetMemory(char* p){p = (char *)malloc(100);}void main(){    char* str = NULL;    GetMemory(str);    strcpy(str, "hello world");    printf(str);}

修改:

方法1:函数参数改为引用

#include <stdlib.h>#include <string.h>#include <stdio.h>void GetMemory(char* &p){p = (char *)malloc(100);}void main(){    char* str = NULL;    GetMemory(str);    strcpy(str, "hello world");    printf(str);}
方法2:传递二级指针

void GetMemory(char** p){    *p = (char *)malloc(100);}int main(void){    char* str = NULL;    GetMemory (&str);    strcpy(str, "hello world/n");    printf(str);    return 0;}



0 0