发送指向函数的指针 [英] send pointer to function

查看:83
本文介绍了发送指向函数的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 我试图按以下方式发送指向函数的指针,但是我的代码有问题,有人可以帮忙吗?

Hi I am trying to send an pointer to a function as following, but there is a problem with my code, can anybody help please:

void fun(int* p1, int* p2, int&s)
{
int size;
cin>>size;
s=size;
p1 = new int[size];
p2 = new int[size];
for(int i =0 ; i<size; ++i)
{
p1[i] = i;
p2[i] = i * i;
}
}
int main()
{
int* p1;
int* p2;
fun(p1,p2,size);
for(int i =0; i< size;++i)
cout<<p1[i]<<" "<<p2[i];
}

推荐答案

您还应该意识到,从fun返回时,您将返回到未初始化的原始p1p2.要实现您要执行的操作,应发送p1p2作为引用,或通过以下方式添加另一个间接级别:
You should also realise that on return from fun you will be back to your original p1 and p2 which are uninitialised. To achieve what you are trying to do you should send p1 and p2 as references, or add another level of indirection thus:
void fun(int*& p1, int*& p2, int&s)
{
int size;
cin>>size;
s=size; // oops - restored this line
p1 = new int[size];
p2 = new int[size];

... // or

void fun(int** p1, int** p2, int&s)
{
int size;
cin>>size
s=size;
*p1 = new int[size];
*p2 = new int[size];
...


考虑使用以下声明:

oid fun(int *&p1,int *&p2,int& s)

因为您需要取消引用指针
consider using this declaration:

oid fun(int* &p1, int* &p2, int&s)

because you need to derefernce the pointers


,所以您没有在main()中声明变量大小,而在fun()
中声明变量s
you didn''t declare variable size in main() and variable s in fun()
<pre lang="cs"><br />
void fun(int* p1, int* p2, int&s)<br />
{<br />
   int size;<br />
   cin>>s;     // replace size by s<br />
<br />
   //s=size;         //comment or remove this line<br />
<br />
   p1 = new int[size];<br />
   p2 = new int[size];<br />
   for(int i =0 ; i<size; ++i)<br />
   {<br />
      p1[i] = i;<br />
      p2[i] = i * i;<br />
   }<br />
}<br />
<br />
int main()<br />
{<br />
<br />
   int size = 0;             // Add this line <br />
<br />
   int* p1;<br />
   int* p2;<br />
   fun(p1,p2,size);<br />
   for(int i =0; i< size;++i)<br />
   cout<<p1[i]<<" "<<p2[i];<br />
}<br />
</pre><br />



复制并编译.



Copy and compile.


这篇关于发送指向函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆