### Dynamically allocating array of structures while also using a function.

I'm playing around with passing a pointer to a structure to a function and found
a way to dynamically allocate an array of structures with a pointer while also using a function. I'm doing something wrong, the program runs through the first time but doesn't the second time.
What would be the appropriate way to delete the dynamically allocated array and solve my problem? Thanks in advance.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748`` ``````#include #include using namespace std; const int length = 40; struct acceleration { char name[length]; double inital_velocity; double final_velocity; double time; }; void formula (acceleration *); int main () { acceleration *cars; cars = new acceleration [3]; for (int count =0; count < 3; count ++) { cout << "Enter the name of the car for car " << (count +1) << ": "; cin.getline(cars[count].name, length); cout << "Enter the initial velocity of the car in meters per second: " << endl; cin >> cars[count].inital_velocity; cout << "Enter the final velocity of the car in meters per second: " << endl; cin >> cars[count].final_velocity; cout << "Enter the car's time to reach final velocity in seconds: " << endl; cin >> cars[count].time; formula (&cars[count]); } cout << fixed << showpoint << setprecision(2) ; return 0; } void formula (acceleration *p){ cout << p->name << "'s acceleration rate is: " << (p->final_velocity - p->inital_velocity)/p->time << endl; }``````
Why don't you just make a private data member as a pointer to a value on the heap? saves you some time...
I'm working with a structure type that deals with the stack rather than the heap. A class would be more efficient but I'm trying to understand both ways of doing things.
closed account (D80DSL3A)
I tried your code and found the only problem is it skips reading in the car name 2nd time around. This is due to an issue with following cin >> with cin.getline().
I inserted `cin.ignore(256,'\n');` at line 35 and this fixed it.
What other problem is there?

You aren't deleting the allocated memory at all. I suggest to insert `delete[] cars;` at line 42.
deallocate memory, and beware of dangling pointers.
That worked out really well. Thanks!
Topic archived. No new replies allowed.