C:如何使用新的找到存储的函数返回值?

我正在阅读Bjarne Stroustrup的第3版C编程语言,并尝试完成所有的练习.我不知道如何从6.6节接近练习13,所以我以为我会转向Stack Overflow来获得一些洞察力.以下是问题的描述:

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.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...