#include<iostream>
using namespace std;
//
1. test 直接修改指针的值,无法成功,改进后可以
/*void getMemory(char*p)
{
p=(char*)malloc(100);
}*/
char* getMemory(char*p)
{
p=(char*)malloc(100);//堆
return p;
}
void test()
{
char*str=0;
str=getMemory(str);
strcpy(str,"hello world");
printf(str);
}
//
2. test 内存在栈里,返回后空间被释放,无法成功
char *GetMemory2(void)
{
char p[]="hello world";//栈
return p;
}
void test2()
{
char*str=0;
str=GetMemory2();
printf(str);
}
//
3. test 通过指针传递指针的值,且申请空间位于堆中,可以成功
void getMemory3(char**p,int num)
{
*p=(char*)malloc(num);
}
void test3(void)
{
char* str=0;
getMemory3(&str,100);
strcpy(str,"hello");
printf(str);
}
//
4. test 已经free掉的内存,再次访问,可以访问,但是存在不安全因素。
void test4(void)
{
char*str=(char*)malloc(100);
strcpy(str,"hello4");
free(str);
if(str!=0)
{
printf("\n");
//printf(str);
strcpy(str,"world");
printf(str);
}
}
int main()
{
test();
test2();
test3();//可以
test4();//free后的指针,指向未分配内存,里面值是随机的,故可能不为0,
char pp[]="helloworld!";//有分配内存,存储"hellowolrd!"可通过数组改变其值
pp[2]='A';
cout<<pp<<endl;
char *ppp="helloworld";//“helloworld”是字符常量,p只是指向该内存区域,不能通过指针改变其值
ppp[2]='A';
cout<<*ppp<<endl;
}
//
内存和指针(测试题2014)
最新推荐文章于 2022-05-29 21:58:46 发布