Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++ question

Name: Anonymous 2005-08-08 18:17

can a function returnan array? i dont think it can, but someone please tell me, it on my C++ final

Name: Anonymous 2005-08-08 18:35

Well, yes and no. Strictly speaking, an array is just a pointer, and functions can return pointers, so yes. However, the array itself is destroyed when it goes out of scope, so the data won't remain intact. You can cheat by declaring the array static, like so:

#include <iostream>

using namespace std;

char *foo()
{
    static char bar[] = "foobar";
    return bar;
}

int main()
{
    char holder, *ptr = foo();
    while(*ptr != '\0')
    {
        holder = *ptr;
        cout << holder;
        ptr++;
    }
    cout << endl;

    return 0;
}

That way, the variable remains in scope, although you can't access it directly.

Of course, in real C++ programming, you'd just use an object.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List