c++ - pointer to string that can be used to dynamically allocate array of strings -
im writing project , car lot , im creating classes. need fullfill requirements. accessory descriptions need use pointer string can used dynamically allocate array of strings exact number of accessories. each element hold name of accessory.
if number of accessories 0, there no need allocate space, set pointer null.
and pointer double can eb used dynamically allocate array of doubles same number of elements accessories. each element hold cost of associated accessory, is, cost in element 0 cost of accessory in element 0. if number of accessories zero, set pointer null since there no need allocate space.
heres class far without last 2 requirements. im stumped.
#ifndef vehicle_h #define vehicle_h class vehicle { public: vehicle(); protected: int vin_number; string manufacturer; string model; string color; double basecost; int accessories; string accessory_list; private: }; #endif // vehicle_h
please it's online course , ive been googling , reading hours.
you should not dynamically allocate array of string
.
if decide use c++, should using stl , collections. this:
std::list<std::string> accessory_list;
if decide use c, dynamically allocated string list this:
//init int accessory_count = 0; int accessory_cap = 20; char** accessory_list = calloc (sizeof(char*), accessorry_cap); //add: if (accessory_count==accessory_cap) { accessory_cap += 20; accessory_list = realloc (accessory_list, sizeof(char*)* accessorry_cap); } accessory_list[accessory_count++] = new_accessory.
if really need dynamic array of strings, can do:
int accessory_arr_cap = 20; string* accessory_arr = new string[accessory_arr_cap];
but since there no realloc possible in case, have copy entire array new 1 if need enlarge it.
Comments
Post a Comment