参考文献:http://wenku.baidu.com/view/02986b4fe518964bcf847c79.html
用指针作为参数,在函数内部申请动态内存,结果改程序会崩溃。要想在函数调用中使用动态内存分配,必须使用二重指针。
错误:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void test(char *ps)
{
ps=(char *)malloc(10*sizeof(char));
}
int main()
{
char *str=NULL;
test(str);
strcpy(str,"abcd");
printf("%s",str);
return 0;
}
改正:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void test(char **ps)
{
*ps=(char *)malloc(10*sizeof(char));
}
int main()
{
char *str=NULL;
test(&str);
strcpy(str,"abcd");
printf("%s",str);
return 0;
}