简体   繁体   中英

Doubling of an arbitrary array of strings

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;}

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM