错误程序--程序崩溃:
#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;
}