我正在练习Alex Allain的数组和指针。
#include <iostream>
#include <fstream>
using namespace std;
int *growArray (int* p_values, int cur_size);
int main ()
{
int next_element = 0;
int size = 10;
int *p_values = new int[ size ];
int val;
cout << "Please enter a number: ";
cin >> val;
while ( val > 0 )
{
if ( size == next_element + 1 )
{
// now all we need to do is implement growArray
p_values = growArray( p_values, size );
}
p_values[ next_element ] = val;
cout << "Please enter a number (or 0 to exit): ";
cin >> val;
}
}
int *growArray (int* p_values, int cur_size)
{
int *p_new_values = new int[ cur_size * 2 ];
for ( int i = 0; i < cur_size; ++i )
{
p_new_values[ i ] = p_values[ i ];
cout << p_new_values[ i ] << endl;
}
delete p_values;
return p_new_values;
}
但是当我执行代码时
Please enter a number: 6
Please enter a number (or 0 to exit): 0
为什么我缺少p_new_values
数组的屏幕输出?是否允许将cout
放入函数定义中?
答案 0 :(得分:5)
if ( size == next_element + 1 )
{
// now all we need to do is implement growArray
p_values = growArray( p_values, size );
}
size
永远不会是next_element + 1
,因此永远不会调用您的growArray
函数。我不确定你用那张支票表达的意思,但你应该重新考虑你的程序的逻辑。
答案 1 :(得分:2)
请注意,当size
仅比当前数组多1个时,next_element + 1
将等于next_element
,因此函数growArray()
将在特定点调用next_element
为size-1
时的程序,等等。
if ( size == next_element + 1 )
{
// now all we need to do is implement growArray
p_values = growArray( p_values, size );
}
此外,变量next_element
无法获取更新以使条件成为有效逻辑。
您可以替换以下行:
p_values[ next_element ] = val;
带
p_values[ next_element++ ] = val;
最终代码:
#include <iostream>
#include <fstream>
using namespace std;
int *growArray (int* p_values, int *cur_size); //Changed
int main ()
{
int next_element = 0;
int size = 10;
int *p_values = new int[ size ];
int val;
cout << "Please enter a number: ";
cin >> val;
while ( val > 0 )
{
if ( size == next_element + 1 )
{
// now all we need to do is implement growArray
p_values = growArray( p_values, &size ); //Changed
}
p_values[ next_element++ ] = val; //Changed
cout << "Please enter a number (or 0 to exit): ";
cin >> val;
}
}
int *growArray (int* p_values, int *cur_size) //Changed
{
*cur_size = *cur_size * 2; //Changed
int *p_new_values = new int[ *cur_size]; //Changed
for ( int i = 0; i < *cur_size; ++i ) //Changed
{
p_new_values[ i ] = p_values[ i ];
cout << p_new_values[ i ] << endl;
}
delete p_values;
return p_new_values;
}
答案 2 :(得分:1)
仅在出现使用*growArray()
函数的情况下才尝试打印值,因为打印语句位于*growArray()
函数内。
在函数定义中使用cout
非常好。
[edit]并且如上所述,您没有改变参数next_element
,所以应该重新检查您的逻辑。