0

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
}
griffin175
  • 131
  • 6

1 Answers1

0

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.

HoleyCow
  • 18
  • 4
  • Can you give me some hints on how I would do that with an array? I'm only able to get the first digit outside the scope of the function. – griffin175 Jun 28 '18 at 03:12
  • 1
    @griffin175 I would suggest using the designated keyword `new` when creating `output[6]`. For example, `char * ctemp = new char[6]` if done this way, the allocated space will need to be freed using `delete' when needed. A lot of others would suggest looking into `std::shared_ptr` if you'd like you can read more about them, [C++ Shared Ptr](https://en.cppreference.com/w/cpp/memory/shared_ptr). – HoleyCow Jun 28 '18 at 03:51
  • I tried `char* ctemp = (char*)malloc(6);` and `char* ctemp = new char[6];` but I get no output on the terminal – griffin175 Jun 28 '18 at 04:21
  • 1
    Nevermind, got it to work. Instead of `char* ctemp = new char[6];` I did `char* output = new char[6];` and `char* ctemp = output;`. Because I'm using pointers to iterate I needed to go back to the first address in the array – griffin175 Jun 28 '18 at 04:37