GetMemory那一题的理解

时间:2023-03-09 03:19:45
GetMemory那一题的理解
#include "stdafx.h"
#include <iostream>
void GetMemory(char *p,int num)
{
p = (char*)malloc(sizeof(char)*num);
}
void GetMemory1(char **p,int num)
{
*p = (char*)malloc(sizeof(char)*num);
}
int _tmain(int argc, _TCHAR* argv[])
{
char *str = NULL;
GetMemory(str,);
GetMemory1(&str,);
strcpy(str,"hello");
return ;
}

对于GetMemory

GetMemory那一题的理解

并没有改变str的指向,这是因为p是str的一个副本,不能代表str,所以运行GetMemory(str,); 时会报错。

对于GetMemory1,利用了指向指针的指针

GetMemory那一题的理解

p中存放的是str的地址,*p实际上就是str的引用,那么对*p的修改实际上就是对str的修改,那么运行GetMemory1(&str,); 就不会报错。