本文介绍了发送指向函数的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨我试图按以下方式发送指向函数的指针,但是我的代码有问题,有人可以帮忙吗?
HiI 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];
}
推荐答案
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];
...
<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.
这篇关于发送指向函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!