改法很多,这里提供两种,具体错误见注释。
方法1:
void GetMemory(char **p){//要改为指针的指针.
if((*p=(char *)malloc(100))==NULL){//要验证是否成功.
printf("Can't get memory...");
exit(0);
}
}
void Test(void){
char *str=NULL;//
GetMemory(&str);//中间不能有=号,应改为GetMemory(&str);
strcpy(str,"hello world");
printf(str);
free(str);//要释放内存.
}
方法2:
char *GetMemory(void){//要改为返回指针.
char *p;
if((p=(char *)malloc(100))==NULL){//要验证是否成功.
printf("Can't get memory...");
exit(0);
}
return p;
}
void Test(void){
char *str=NULL;//
str=GetMemory();//改为把返回的指针赋给str
strcpy(str,"hello world");
printf(str);
free(str);//要释放内存.
}
这两种改法都可以用下面的代码调用验证:
void main(void){
Test();
printf("\n");
}