简体   繁体   中英

I need to dynamically resize an array of objects

I need to dynamically resize my array by 2 every time it fills up. It starts with a capacity of 2. This is what I've done (in main.cpp), but it gives me these errors: "warning: deleting array 'test'" and "error: incompatible types in assignment of 'ItemInfo*' to 'ItemInfo [cap]'".

ItemInfo test[cap];

//I have code here to open file, read from file, etc

if(itemCount >= cap){
    cap += 2;
    ItemInfo *temp;
    temp = new ItemInfo[cap];
    for(int i = 0; i < cap; i++){
        temp[i] = test[i];
    }
    delete[] test; //error here
    test = temp;   //error here
}

This is the class (in.hpp file):

#include <iostream>
#include <iomanip>

using namespace std;

class ItemInfo {
private:
    int itemId;
    char description[40];
    double manCost;
    double sellPrice;
public:
    ItemInfo() {
        itemId = 0;
        *description = '\0';
        manCost = 0.0;
        sellPrice = 0.0;
    }
    void setItemId(const char *num);
    void setDescription(const char *cstr);
    void setManCost(const char *num);
    void setSellPrice(const char *num);
    int getItemId();
    const char *getDescription();
    double getManCost();
    double getSellPrice();

The problem is that you use ItemInfo test[cap]; . Using this declaration results in test being saved on the stack. Therefore, it has constant size. Using temp = new ItemInfo[cap]; dynamically allocates memory on the heap. This is the memory which you can also free. Thus, test and temp are different types and test cannot be freed. ItemInfo *test = new ItemInfo[cap]; should work for you.

Also mind that there is another small mistake: You copy the first cap many values after increasing cap where the old cap should be used.

You could use realloc too if ItemInfo is trivially copyable so that you do not need the loop to copy the data and temporarily use more memory than maybe needed. The code for using realloc would seem like

ItemInfo *test = (*ItemInfo) malloc(cap * sizeof(ItemInfo));
// use malloc here as realloc and new should not be mixed
[...]
if(itemCount >= cap){
    cap += 2;
    test = (*ItemInfo) realloc(test, cap * sizeof(ItemInfo));
}

As user4581301 mentioned you could also try to use Vectors if there is nothing specific against it.

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