Search code examples
c++guideline-support-library

Can I return a span in C++? If so, how? (Open to alternatives.)


The project guide for an assignment I've been given specifically barred the use of vectors and strings, but I need to pass a char array of indeterminate size from a function. The use of span seems like it might be viable for this purpose if I can better understand how it is used. If anyone could recommend a better/different means of passing arrays (aside from strings and vectors) I would love to learn about it.

I have considered generating a scratch file and storing input text there for recall elsewhere in the program, but that seems rather more cumbersome than should be necessary in this case. This program will also be small enough that I could do everything in main, but that also shouldn't be necessary.

What I would like to do is to be able to call a function like this:

span<char> getSpan(){
    char arr[] = { 'A', 'B', 'C' };
    span<char> spanOut{ arr };
    return spanOut;
}

and then print the contents of spanOut from main:

int main() {
    // Some Code...
    printSpan = getSpan();
    std::cout << printSpan;
}

Ideally, the result of the above code would be to have ABC printed to the terminal.


Solution

  • It turns out that Anonymous Anonymous was correct, the instructor wanted me to use dynamically allocated memory. I had been getting too "clever" for my own good, and missing the obvious in favor of complexity. Thank you, L.F., for your excellent breakdown of span :)