Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: How to use new to find store for function return value?
    text
    copied!<p>I'm reading the 3rd edition of <em>The C++ Programming Language</em> by Bjarne Stroustrup and attempting to complete all the exercises. I'm not sure how to approach exercise 13 from section 6.6, so I thought I'd turn to Stack Overflow for some insight. Here's the description of the problem:</p> <blockquote> <p>Write a function <em>cat()</em> that takes two C-style string arguments and returns a single string that is the concatenation of the arguments. Use <em>new</em> to find store for the result.</p> </blockquote> <p>Here's my code thus far, with question marks where I'm not sure what to do:</p> <pre><code>? 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; } </code></pre> <p>And here are my questions:</p> <ol> <li>How do I use <em>new</em> to find store? Am I expected to do something like <code>std::string* result = new std::string;</code> or should I be using <em>new</em> to create another C-style string somehow?</li> <li>Related to the previous question, what should I return from cat()? I assume it will need to be a pointer if I must use <em>new</em>. But a pointer to what?</li> <li>Although the problem doesn't mention using <em>delete</em> to free memory, I know I should because I will have used <em>new</em> to allocate. Should I just delete at the end of main, right before returning?</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload