运行代码

1 #include <iostream>
2
3 void GetMemeory(char *p)
4 {
5 p = (char *)malloc(100);
6 }
7 void Test()
8 {
9 char *str = NULL;
10 GetMemeory(str);
11 strcpy(str, "Thunder");
12 strcat(str + 2, "Downloader");
13 printf(str);
14 }

运行结果

程序崩溃

程序解释

首先,函数为按值传递,所以p和str指向的是同一个NULL;

GetMemory函数执行完后,为p指向的空间增加了内存空间,但str仍然指向NULL;

要修改实参,就要传递实参的地址,因此需要传递二级指针,修改如下:

1 void GetMemory(char **p){
2 *p = (char *)malloc(100);
3 }
4
5 void Test(){
6 char *str = NULL;
7 GetMemory(&str);
8 strcpy(str,"Thunder");
9 strcat(str+2,"Downloader");
10 printf(str);
11 }