FinnAwe / Cpp-Practice

Reinvent Wheels To Learn
0 stars 0 forks source link

How to implement c_str() #2

Open FinnAwe opened 6 years ago

Ujjval-Patel commented 6 years ago

Hello FinnAwe, you can always refer cplusplus. Here you can find solution of most of basic doubts. BTW, here's solution of your Issue const char* c_str() const//available only after MyString was created { MyString *ptr = const_cast<MyString*>(this); ptr->data_array_c_str = new char[data_length + 1]; copy(data_array_c_str, data_length, 0); data_array_c_str[data_length] = '\0'; return data_array_c_str; } which is found in cplusplus.

FinnAwe commented 6 years ago

Hello FinnAwe, you can always refer cplusplus. Here you can find solution of most of basic doubts. BTW, here's solution of your Issue const char* c_str() const//available only after MyString was created { MyString *ptr = const_cast<MyString*>(this); ptr->data_array_c_str = new char[data_length + 1]; copy(data_array_c_str, data_length, 0); data_array_c_str[data_length] = '\0'; return data_array_c_str; } which is found in cplusplus.

Thank you, Ujjval, your code is vering inspiring. For the detail, if the c_ctr be called twice, isn't it cause memory leak?