标签:分配 string amp 指针 rcp main print 地址 %s
#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);
}
}
标签:分配 string amp 指针 rcp main print 地址 %s
原文地址:https://www.cnblogs.com/embeddedking/p/9697203.html