..............................
void GetMemory(char *p,int num)
{
p=(char *)malloc(sizeof(char) *num);
};
int main()
{
char *str=NULL;
GetMemory(str,100);
strcpy(str,"hello");
return 0;
}
GetMemory(char p,int num)中的p实际上是主函数中str中的一个副本,编译器总是要为函数的每个参数制作临时副本。在上述例程中,P申请了新的内存,只是把p所指的内存地址改变了,但是str丝毫未变。因为函数GetMemory没有返回值,因此str并不指向p所申请的内存。
2.若要用指针参数去申请内存,应该采用指向指针的指针。
void GetMemory(char **p,int num)
{
p=(char *)malloc(sizeof(char) *num);
};
int main()
{
char *str=NULL;
GetMemory(&str,100);
strcpy(str,"hello");
return 0;
}
3.函数返回值来传递动态内存地址
void GetMemory(char *p,int num)
{
p=(char *)malloc(sizeof(char) *num);
};
int main()
{
char *str=NULL;
GetMemory(str,100);
strcpy(str,"hello");
return p;
}
可以实现内存的成功申请
4.整型变量如何传值
void GetMemory2(int *z)
{
*z=5;
};
int main()
{
int v;;
GetMemory2(&v);
printf("%d",v)
return 0;
}
GetMemory2把v的地址传了进来,*z是地址里的值,是v的副本,通过直接修改地址里的值,不需要有返回值。