原来的题目为
GetMemory(char *p)
{
p=(char *)malloc(100);
}
main()
{
char *str=NULL;
GetMemory(str);
strcpy(str, "hello ");
printf(str);
}
可以返回新申请内存的地址.改法如下:
unsigned int GetMemory(char *p)
{
p=(char *)malloc(100);
return (unsigned int)&p;
}
main()
{
char *str=NULL;
unsigned int addr;
addr=GetMemory(str);
str = (char*)*( (unsigned int *)addr );
strcpy(str, "hello ");
printf(str);
free(str);
str=NULL;
}
也可以用指针引用.改法如下:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
void GetMemory(char * &p)
{
p=(char *)malloc(100);
}
void main()
{
char *str=NULL;
GetMemory(str);
strcpy(str, "hello ");
printf(str);
printf("%x",str);
free(str);
str=NULL;
//rintf("%x",str);
}
还可以用指向指针的指针.改法如下:
void GetMemory(char ** p)
{
*p=(char *)malloc(100);
}
void main()
{
char *str=NULL;
GetMemory(&str);
strcpy(str, "hello ");
printf(str);
free(str);
str=NULL;
}