0

please, why this pointer array won't accept more than 5 values?

Doing excercises from Prata's C++ book, but got stuck on this.

//ex2_numrow -- showing entered numbers til zero is entered 
#include <iostream>
using namespace std; 

int main()
{
    int n = 0;
    int num = 0; 
    int* entered = new int[1]; 

    do
    {
        cout << "Enter number: ";
        cin >> num;
        entered[n] = num;                       

        cout << "Your numbers: ";       
        for (int i = 0; i <= n; i++)
        {
            cout << entered[i] << " ";          
        }

        cout << endl << endl;
        n++;

    } while (num);
    delete[] entered;

    return 0;
}
Stnly83
  • 3
  • 1

1 Answers1

2

The code int* entered = new int[1]; gives you a pointer to an array of size one!

It is very unwise (i.e., undefined behaviour) to then try to write values outside of that array. The best case is that your code will crash before it causes any serious issues.

As an aside, the set of use cases for raw pointers is fast dwindling in C++, you should generally be looking at smart pointers instead.

I say "generally" because, if your intent is to have a resizable array, even smart pointers won't help that much. What will help is a little thing I like to call std::vector :-) You should probably look into using that for your immediate purpose.

For example, this program accepts positive numbers, adding them to a vector, then printing them out:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers;
    int num;

    do {
        std::cout << "Enter number: ";
        std::cin >> num; // should probably check for errors in real code
        if (num >= 0) {
            numbers.push_back(num);
        }
    } while (num >= 0);

    std::cout << "You entered:";
    for (int num: numbers) {
        std::cout << ' ' << num;
    }
    std::cout << '\n';
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Thx, but how to define ponter array where I don't know how many values will user enter? the empty [] doesn't work. – Stnly83 Nov 16 '19 at 06:18
  • @Stnly83, see the update. You *don't* do that. Instead, you use `vector` which gives you pretty much everything you seem to be after. – paxdiablo Nov 16 '19 at 06:19
  • @Stnly83 when you do use `std::vector`, don't try to add elements like `vec[n] = num`. That's undefined too if vector doesn't have enough elements. Instead do this `vec.push_back(num)`. – Aykhan Hagverdili Nov 16 '19 at 06:21