简体   繁体   中英

How to create dynamic struct array in C++?

Im trying to learn dynamic arrays in C++. For integer, dynamic arrays are like that:

int main()
{    
    int x;
    cin >> x;

    int *dynamic = new int[x];
    //some codes
    delete [] dynamic;

    return 0;
}

How can i create dynamic struct array? I tried this code and i failed.

struct Phone{
    char name[30];
    char number[20];
}

int main(){
    int x;
    cin >> x;

    Phone *record;
    Phone *record = new Phone[x];// Code fails here

}

Im so confused in dynamic arrays. Please help me. Thanks.

There is no difference in syntax between allocating an int and allocating a struct .

Your syntax is correct. You're just defining the record pointer twice. Remove the first definition and you're all set (oh, and missing a semicolon after the struct{} declaration).

Note that modern C++ would probably prefer using an existing STL container ( vector<Phone> or similar) instead of manually calling new and delete[] . I assume this is for learning, not for production code.

I would also suggest to rather use an std::vector. It's going to save you a lot of issues and memory bugs. Just do:

struct structName 
{
     ...
}

std::vector<structName> structVector;

Then to get the values onto the vector do a

 structVector.push_back(structName{});

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