指针值传递、指针的指针、指针的引用、无法返回临时变量地址

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void GetMemory(char *p)
{
//char *p = str, p = str(值传递,跟str无关,内存分配失败)
p = (char*)malloc(100);
}
void GetMemory1(char **p)
{
//char **p = &str, p指向str指针的地址,*p指向str的地址,*p = str, *p分配内存即str分配内存成功
*p = (char*)malloc(100);
}
void GetMemory2(char* &p)
{
//p是str的引用,p还是str ,
p = (char*)malloc(100);
}
char* GetMemory3(void)
{
char p[] = "Hello World";
return p; //无法返回临时变量的地址
}
//int main(void)
//{
// char *str=NULL;
//// GetMemory(str);
//// GetMemory1(&str);
//// GetMemory2(str);
//// strcpy(str,"Hello world");
// str = GetMemory3();
// printf(str);
// return 0;
//}

int main(void)
{
char *str = (char*)malloc(100);
strcpy(str, "Hello");
// printf("first is %s\n",str);
free(str);
if(str != NULL)
{
strcpy(str, "World");
printf(str);
}
}

猜你喜欢

转载自www.cnblogs.com/embeddedking/p/9697203.html
今日推荐