Search code examples
c++coutc-strings

Function Output Problems


I made a function to convert an array of ints (a zipcode) into a cstring. If I call the function, the return is gibberish, but if I cout the returned variable inside the function it's exactly as expected.

const char* print_zip(const int* zip) {
    char output[6];
    char* ctemp = output;
    const int *itemp = zip;
    for (int i = 0; i < 5; i++) {
        *ctemp = *itemp + 48;       // convert to char numbers.
        itemp++;                    // iterate using pointers rather than []
        ctemp++;                    // per assignment specifications
    }
    *ctemp = '\0';
    std::cout << output << std::endl;   // (debug only) as expected
    return output;                  // cout << print_zip(); not as expected
}

Solution

  • When you cout the return variable inside the function, it should be expected to return the value wanted. This is because when you create a local variable inside a function it resides in that function's stack frame. Thus, when STILL inside the function, the scope is still set to see that variable.

    On the contrary, when the pointer to the local variable is returned, the stack frame no longer exists, basically meaning the pointed to object could or could not be complete junk.

    In order to return a variable that will be constant within or out of the stack frame, you would need to pass it by reference, which is usually done by making a copy of object your trying to return, then returning that copy.