I have following C code:
char* ToHex(char input)
{
char output[3];
char* HexArray = "0123456789ABCDEF";
output[0] = HexArray[(input / 16)];
output[1] = HexArray[input % 16];
output[2] = '\0';
return output;
}
void main()
{
char* ptr = ToHex('a');
char string[20];
strcpy_s(string, 20, ptr);
printf(string);
}
I'm trying to make a function that converts chars to hex.
Function works great and when debugging in Visual C ptr == "61".
Then when printing pointer I get: "¹⌂".
Now if I copy ptr into string and then print string, I see the expected "61".
Can anyone tell me what is going on?
How can I make it so whatever is returned by ToHex is properly printed?
Edit: made it work by using char *output = malloc(3), though I still don't understand the gist of local scope.
I get the var stops existing, but why did it print the correct output when copying outside of the local scope?