加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:53:37 所属栏目:百科 来源:网络整理
导读:我正在阅读Bjarne Stroustrup的第3版C编程语言,并尝试完成所有的练习.我不知道如何从6.6节接近练习13,所以我以为我会转向Stack Overflow来获得一些洞察力.以下是问题的描述: Write a function cat() that takes two C-style string arguments and returns a
我正在阅读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 != '')
    {
        current = first[i];
        // somehow append current to whatever will eventually be returned
        i++;
    }

    current = '';
    i = 0;

    while (current != '')
    {
        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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读