C/C++中的函数传值
一、运行如下程序段
1 #include <iostream> 2 #include <string> 3 #include <cstring> //strcpy 4 #include <cstdlib> //malloc 5 #include <cstdio> //printf 6 7 using namespace std; 8 9 void GetMemory(char* p){ 10 p = (char*)malloc(100); 11 } 12 13 int main(){ 14 char *str = NULL; 15 GetMemory(str); 16 strcpy(str,"Thunder"); 17 strcat(str+2,"Downloader"); 18 printf(str); 19 20 return 0; 21 }
分析:程序崩溃。在函数中给指针分配空间,实际上是给指针的临时变量分配空间,函数结束后临时变量消亡,str仍然为NULL。改变指针需要传入二级指针。函数名需改为
1 void GetMemory(char* &p)