c++ - How to print out a struct pointer? -


i'm trying print out structs have made inside function, , since these must available outside of function have used pointers. have declared struct , functions in header file:

struct car{ double wheeldiam; int numberofwheels; string brand; };  void makecars();  ostream & operator<<( ostream & out, const car & elem ); void printcar( car car); 

the function makes cars looks this:

void  makecars(){     car *astonmartin;     car *volvo;     car *audi;     audi->numberofwheels = 4;     audi->wheeldiam = 20.0;     audi->brand = "audi";     volvo->numberofwheels = 4;     volvo->wheeldiam = 23.0;     volvo->brand = "volvo";     astonmartin->numberofwheels = 5;     astonmartin->wheeldiam = 25.0;     astonmartin->brand = "aston martin";  } 

and have made function prints out struct (overloaded operator=):

ostream & operator<<( ostream & out, const car & elem ){     out << elem.brand<<"  "<<elem.numberofwheels <<"   "<<elem.wheeldiam<<endl;     return out; }  void printcar( car car){     cout << car << endl; } 

but when call functions in main() doesn't print , error message:

int main(){  makecars();  printcar(*astonmartin); return 0 } 

whats correct way this?

first of all, declare variable car * astonmartin in function. variable exists only in makecars function.

you can't use object or delete it

a better way

void setcarattributes(car *c) {    // set car    c->setbrand("aston martin");    // etc ... }  void printcar() {    // print want 

  }

int main() {     car *astonmartin = new car();     setcarattributes(astonmartin);     printcar(astommartin); } 

nevermind variable declare in functions can't used in other functions. use variable everywhere need declare global variable in case it's not necessary declare car * , give parameter functions


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -