1

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.

5
  • 1
    What does the actual error message say? Commented Sep 21, 2014 at 18:58
  • Program breaks when i tried to enter record[0].name and number Commented Sep 21, 2014 at 19:00
  • 1
    What makes you think having two record declarations is necessary (or allowed) just because the type changed? Commented Sep 21, 2014 at 19:00
  • I tried the code without Phone *record; Commented Sep 21, 2014 at 19:02
  • shldn't it be Phone *record = new Phone; then *record.name = something and *record.number = something? btw number should be of type int? Commented Sep 21, 2014 at 19:05

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you suggest me a source about that (especially structs)?
I would just refer to Stroustrup's "The C++ Programming Language", but depending on your experience you might be looking for a more beginner-friendly book.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.