#include <iostream>
#include <stdlib.h>
using namespace std;
void GetMemory(char **p, int num) {
*p = (char*)malloc(num*sizeof(char));
}
char * GetMemory2(char *p,int num) {
p = (char*)malloc(sizeof(char)*num);
return p;
}
int main(int argc, char *argv[])
{
char *str=NULL;
GetMemory(&str, 10);
strcpy(str, "method 1");
printf("%s", str);
free(str);
GetMemory2(str, 10);
strcpy(str, " method 2");
printf("%s", str);
free(str);
system("PAUSE");
return 0;
#include <stdlib.h>
using namespace std;
void GetMemory(char **p, int num) {
*p = (char*)malloc(num*sizeof(char));
}
char * GetMemory2(char *p,int num) {
p = (char*)malloc(sizeof(char)*num);
return p;
}
int main(int argc, char *argv[])
{
char *str=NULL;
GetMemory(&str, 10);
strcpy(str, "method 1");
printf("%s", str);
free(str);
GetMemory2(str, 10);
strcpy(str, " method 2");
printf("%s", str);
free(str);
system("PAUSE");
return 0;
}
如果用:
void GetMemory(char * p, int num)
{
p = (char *)malloc(num*sizeof(char));
}
是不行的,因为main中的指针是局部变量,函数调用时将指针拷贝后传递给一个临时指针变量假设为pclone到函数内部,只是改变了pclone的指向,没有改变原指针的值,会造成memory leak