Write a function cat() that takes two C-style string arguments and
returns a single string that is the concatenation of the arguments.
Use new to find store for the result.
这是我的代码到目前为止,有问号,我不知道该怎么办:
? cat(char first[],char second[]) { char current = ''; int i = 0; while (current != '\0') { current = first[i]; // somehow append current to whatever will eventually be returned i++; } current = ''; i = 0; while (current != '\0') { current = second[i]; // somehow append current to whatever will eventually be returned i++; } return ? } int main(int argc,char* argv[]) { char first[] = "Hello,"; char second[] = "World!"; ? = cat(first,second); return 0; }
这里是我的问题:
>如何使用新的查找商店?我期望做一些像std :: string * result = new std :: string;还是应该用新的来创建另外一个C风格的字符串?
>与上一个问题相关,我应该从cat()返回什么?我认为如果我必须使用新的,它将需要一个指针.但指向什么?
>虽然问题没有提到使用删除来释放内存,我知道我应该因为我会使用新的分配.我应该在main的最后删除,在返回之前?
解决方法
How do I use new to find store? Am I expected to do something like
std::string* result = new std::string;
or should I be using new to create another C-style string somehow?
后者;该方法采用C风格的字符串,并且文本中没有任何内容表明它应该返回任何其他字符串.因此,函数的原型应该是char * cat(char const *,char const *).当然这不是你通常写功能的方式;手动内存管理在现代C中完全禁忌,因为它很容易出错.
Although the problem doesn’t mention using delete to free memory,I know I should because I will have used new to allocate. Should I just delete at the end of main,right before returning?
在这个练习中,是的.在现实世界中,不,就像上面所说的,这完全是禁忌.实际上你会返回一个std :: string,而不是使用new来分配内存.如果你发现自己手动分配内存(并且假设它是很好的理由),那么你会把这个内存不是一个原始的指针,而是一个智能指针 – std :: unique_ptr或std :: shared_ptr.