指针作为函数的返回值
实例1
#include<iostream>
using namespace std;
char * fun()
{
char *p = new char[100];
char a[100] = "hello world";
p = a;
cout<<p;
return p;
}
int main()
{
char *s ;
s = fun();
cout<<s<<endl;
return 0;
}
输出:乱码
猜想:1 s没有分配内存空间
实例2
#include<iostream>
using namespace std;
char * fun()
{
char *p = new char[100];
char a[100] = "hello world";
p = a;
cout<<p;
return p;
}
int main()
{
char *s = new char[100];
s = fun();
cout<<s<<endl;
return 0;
}
输出: 乱码
猜想错误
猜想:临时变量的地址无法传递给调用者
实例3
#include<iostream>
using namespace std;
char a[100] = "hello world";
char * fun()
{
char *p = new char[100];
p = a;
cout<<p;
return p;
}
int main()
{
char *s = new char[100];
s = fun();
cout<<s<<endl;
return 0;
}
输出:helloworld helloworld
实例1
#include<iostream>
using namespace std;
char * fun()
{
char *p = new char[100];
char a[100] = "hello world";
p = a;
cout<<p;
return p;
}
int main()
{
char *s ;
s = fun();
cout<<s<<endl;
return 0;
}
输出:乱码
猜想:1 s没有分配内存空间
实例2
#include<iostream>
using namespace std;
char * fun()
{
char *p = new char[100];
char a[100] = "hello world";
p = a;
cout<<p;
return p;
}
int main()
{
char *s = new char[100];
s = fun();
cout<<s<<endl;
return 0;
}
输出: 乱码
猜想错误
猜想:临时变量的地址无法传递给调用者
实例3
#include<iostream>
using namespace std;
char a[100] = "hello world";
char * fun()
{
char *p = new char[100];
p = a;
cout<<p;
return p;
}
int main()
{
char *s = new char[100];
s = fun();
cout<<s<<endl;
return 0;
}
输出:helloworld helloworld