I have a question. I have the following struct:
typedef struct{
int vin;
char* make;
char* model;
int year;
double fee;
}car;
Then I have the following method that asks the user for the make of a car and returns it as a char pointer:
char* askMake(){
char* tempMake = NULL;
cout << "Enter Make:" << endl;
cin >> tempMake;
return tempMake;
}
Then I have a temp car struct:
car tempCar;
And I am trying to assign a value to it this way:
tempCar.make = askMake();
It compiles fine, but I get a segmentation fault at runtime.
You have to allocate memory for
tempMake.Try this:
Don’t forget to free with
delete[]the memory that you allocated.If you don’t want memory leaks, you can avoid this using smart pointers like boost::shared_ptr or boost::scoped_ptr or similar. You can see more about this here.