Originally posted by: dude8604
I know about how they are similar, but I have never seen/used malloc(). Please explain to me what it does.
malloc is used to dynamically allocate memory. Instead of being created on the STACK, it's created on the HEAP. You the programmer are required to FREE UP memory that's allocated on the HEAP.
Anyway, there's an easier way to accomplish what you're trying to do:
void DecimalToHex(int num, char *hexBuffer)
{
if (num < 16)
{
if (num < 10)
{
hexBuffer[0] = num + 48;
}
else hexBuffer[0] = (num-10) + 65;
}
else DecimalToHex(num/16, hexBuffer+1);
/* Note: the "hexBuffer+1" call above causes DecimalToHex to be passed "hexBuffer" */
/* such that hexBuffer[0] is the next character over to the right. Thus, by virtue of */
/* your recursive algorithm, your hex value will actually be populated RIGHT TO LEFT */
}
int main()
{
/* Define a HEX BUFFER up to 16 characters long (plus 1 character for NULL terminator) */
char hex[16+1];
int num = 1164;
/* NULL out the "hex" storage buffer */
memset(hex, NULL, 16+1);
/* Convert the decimal number to hex. Result gets stored in "hex" storage buffer. */
DecimalToHex(num, hex);
/* Now output the results. Note: cout is a c++ construct. Thus, this code is really ENHANCED C
😀 */
cout << "Decimal: " << num << "." << endl;
cout << "Hexadecimal: " << hex << "." << endl;
return 0;
}
Hit
Quote to see the FORMATTED version of the code above.
*EDIT* BTW, there's IMO a major flaw w/ the recursive logic above. Any time DecimalToHex gets called w/ a num value > 16, no data will be written to the passed in hexBuffer at hexBuffer[0]. It will immediately be sent back into DecimalToHex w/ hexBuffer+1 (which is the same thing as the previous call's hexBuffer[1]). To make your logic correct, right after that recursive call to DecimalToHex, you need to populate hexBuffer[0] with SOMETHING./