0

(im still learning c++ and wanted to try and make my own Int to String function, so apologies if what ive done doesn't fit any standards...)

i made this function to convert ints to a string (well, a const char*), this is the code here:

#include <iostream>
#include <vector>

char IntToChar(int value) {
    if (value < 0 || value > 9) {
        return '0';
    }

    return (char)(value + 48);
}

const char* IntToString(int value) {
    char buffer[11];
    memset(&buffer, 0, sizeof(buffer));

    std::vector<int> splitValue;
    while (true) {
        splitValue.insert(splitValue.begin(), value % 10);
        value /= 10;
        if (value == 0)
            break;
    }

    for (int i = 0; i < splitValue.size(); i++) {
        buffer[i] = IntToChar(splitValue[i]);
    }

    splitValue.clear();
    return buffer;
}

int main()
{
    int value = 123789;
    const char* valueString = IntToString(value);

    std::cout << valueString << '\n';
}

but when i write valueString to cout (the console), the number is nowhere to be seen; it's just random characters. i debugged the entire function and found it successfully turned the numbers into chars and returned those chars in an array. what could be going wrong here? i assume it's because it returns an array who's length is 11 but only a few elements are filled (for a small number). but i could be wrong

edit: issue was that the buffer was getting killed just as the function ends due to it being a pointer (i assume). so i replaced const char* with std::string, and where i actually added the code to the buffer, instead of buffer[i], i did buffer +=.

REghZY
  • 69
  • 1
  • 7
  • `buffer` is local variable. It dies as soon as function `return`s and the memory can be reused for any other purpose. – Yksisarvinen Aug 31 '20 at 19:57
  • 3
    You're probably better off returning a `std::string` rather than a `const char *`. – jkb Aug 31 '20 at 20:00
  • oh i see. i made the buffer a global variable and it works now, thanks. – REghZY Aug 31 '20 at 20:01
  • 3
    @TheRR *i made the buffer a global variable and it works now, thanks* -- Making it global is just as bad as the original problem. – PaulMcKenzie Aug 31 '20 at 20:03
  • yeah, i realised that. i instead replace const char* with std::string, and it seems to work fine now. thanks a lot – REghZY Aug 31 '20 at 20:08
  • Your local variable goes out of scope (no longer exists) as the function ends but you return a pointer to it. The pointer is not usable. It's undefined behavior dereference it. – drescherjm Aug 31 '20 at 20:14
  • Using a vector makes things complicated (IMO). When using `std::string` it can be like: https://ideone.com/VUaecM – Support Ukraine Aug 31 '20 at 20:41

0 Answers0