0

1: My goal is to create two arbitrary arrays using pointers: one with names, another one with corresponding numbers. From my previous question, I know that doubling an array is a good way to deal with arbitrary sizes. So, I am trying to double both arrays correspondingly. But while the doubling of an int array goes well, array of strings does not double. Could you explain, what is the problem with that?

2: Is there an alternative to the creation of arbitrary array of strings to store list of names?

Here is the part of the code:

string *pn = new string [size];
int *pd = new int [size];
while (x != 0) {

    if (size == k+1) {
        pn = doubn (pn, size);
        pd = doubd (pd, size);
    }
    pn[k] = name;
    pd[k] = val;
    cout << "Another entry? (0 for exit)";
    cin >> x;
    getline (cin, name, ',');
    cin >> val;
    ++k;
}

for (int i = 0; i<k; ++i) {

    cout << pn[i] << " - " << pd[i] << " days"; }
del (pn, pd, k);
cin.get ();
cin.ignore();
}

string* doubn (string *pn, int size) {

    string* pnn = new string [size*2];
    for (int i = 0; i < size; ++i) {

        pnn [i] = pn[i]; }

    delete pn;
    return pnn; }

int* doubd (int *pd, int size) {

    int *pdn = new int [size*2];
    for (int i = 0; i<size; ++i) {
        pdn [i] = pd[i];}
    delete pd;
    return pdn;}
VVG
  • 141
  • 1
  • 13
  • Relevant: [mixing cin and getline](http://stackoverflow.com/questions/6642865/getline-not-asking-for-input) – Barry Feb 12 '15 at 12:38
  • You need `delete [] pn;` and `delete [] pd;`, otherwise your program is undefined. But you really should use `std::vector`, as it's already handling all this for you. – molbdnilo Feb 12 '15 at 12:46

2 Answers2

1

To have arbitrary sized arrays, use vectors.

Vectors are a part of the C++ Standard Template Library (STL) and required the #include<vector> header.

For more information, check this out: http://www.cplusplus.com/reference/vector/vector/

Also, you should be using delete [] instead of delete.

therainmaker
  • 4,253
  • 1
  • 22
  • 41
0

You use delete on memory allocated by new[], you should use delete[] instead.

Using std::vector would be simpler and less error prone anyway.

Jarod42
  • 203,559
  • 14
  • 181
  • 302