带有数组指针的c ++内存位置

时间:2016-12-09 15:12:49

标签: c++ pointers memory

我有以下代码:

#include <iostream>
using namespace std;

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 ];
    }
    delete p_values;
    return p_new_values;
}
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 )
        {
            cout<< "Im in If"<<endl;
            p_values = growArray( p_values, size );
        }
        p_values[ next_element ] = val;
        cout << "Please enter a number (or 0 to exit): ";
        cin >> val;
    }

}

此代码动态分配内存。我可以理解这段代码中的所有内容,只需要做一件事。这个的目的是什么?无论我给出了多少输入,如果是,程序将永远不会进入。

1 个答案:

答案 0 :(得分:1)

您永远不会增加最初等于0的变量next_element的值

int next_element = 0;

因此,if语句中的表达式不会被计算为true,而是会覆盖相同的第一个元素

p_values[ next_element ] = val;

程序整体上有错误的逻辑。例如,if语句应该看起来像

 if ( size == next_element )
      ^^^^^^^^^^^^^^^^^^^^
 {
     cout<< "Im in If"<<endl;
     p_values = growArray( p_values, size );
     size *= 2;
     ^^^^^^^^^
 }

这句话看起来应该是

p_values[ next_element++ ] = val;
                   ^^^^^

while循环应该看起来像

cout << "Please enter a number: ";
while ( cin >> val && val > 0 )
{
    //...
    cout << "Please enter a number (or 0 to exit): ";
}