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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <iomanip>
 
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.