Hello guys, thanks for checking my question. First, I'm really sorry about the thread title if it's confusing and unspecific. I lack proper english and knowledge of c++ to explain the problem in short sentence :(
Anyway, I got an assignment and part of that assignment is to create a class with an overloaded constructor that accept a hexadecimal string which will be stored as an int. I have figured out how to convert hex string and store as an int. Now they want me to create a function that returns the decimal value as an hexadecimal string.
Here is the code that i write quickly in main function:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main()
{
int number = 266;
char buffer[20];
itoa(number, buffer,16);
cout<<buffer;
}
that code runs fine without any error, but when i try to convert it as a function, like this:
it compiles without error but when i ran it some weird characters show up!
i ran the code on my friend's borland C++ and somehow it display correctly, but not on mine (i used CodeBlocks). why is that? does anyone have any idea? Thanks :(
char inHex[25]; is a local definition. After exiting the function the stack occupied by this definition can be overwritten.
I think that your function shall follow the interface of standard C function itoa that is it shall have two parameters the original number and the character array where the result will be written.
You are returning a pointer with the memory address of a local variable.
Local variables are stored on the stack memory area.
When the function ends its stack section becomes unsafe to use.
Plain English: you can't know what will happen if you try to use a local variable after its daddy function ends!
Solution: return a copy instead of a pointer. And use modern C++ elements while you're at it.
thanks for the reply vlad and catfish23. seems like i missed a lot of things to study. and your explanation is good, i'm glad i asked here.
this is the first time i used stringstream, i'll figure out how it works! my college never even mentioned this. haha. anyway thank you guys!