如何在屏幕上显示输出?

时间:2015-08-18 08:10:02

标签: c++ arrays

我正在练习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放入函数定义中?

3 个答案:

答案 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_elementsize-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,所以应该重新检查您的逻辑。