Home > Blockchain >  _itoa_s doesn't accept dynamic array
_itoa_s doesn't accept dynamic array

Time:12-08

I am new to C and dynamic memory allocation.

I have this code to convert a number from decimal to hexadecimal, that uses a dynamic array:

int hexLen = value.length();
char* arrayPtr = new char[hexLen];

_itoa_s(stoi(dec), arrayPtr, 16);

string hexVal = static_cast<string>(arrayPtr);

delete[] charArrayptr;

When I used an array with a fixed size, _itoa_s() worked with it. However, when using a dynamic array, the compiler says that a method with the arguments given doesn't exist.

Is this something that I did wrong, or will _itoa_s() simply not work with a dynamic array?

Version with non-dynamic array (that works):

const int LENGTH = 20;
char hexCharArray[LENGTH];

_itoa_s(stoi(dec), hexCharArray, 16);

CodePudding user response:

If you read the documentation carefully, you would see that you are trying to call the template overload of _itoa_s() that takes in a reference to a fixed-sized array:

template <size_t size>
errno_t _itoa_s( int value, char (&buffer)[size], int radix ); 

You would need to instead call the non-template overload that takes in a pointer and a size:

errno_t _itoa_s( int value, char * buffer, size_t size, int radix );

Try this:

int decValue = stoi(dec);

int hexLen = value.length();
int arraySize = hexLen   1; //  1 for null terminator!

char* arrayPtr = new char[arraySize];

errno_t errCode = _itoa_s(decValue, arrayPtr, arraySize, 16);
if (errCode != 0)
{
    // error handling...
}
else
{
    string hexVal = arrayPtr;
    // use hexVal as needed...
}
delete[] charArrayptr;

Since you are trying to get the hex into a string, you can do away with the char* altogether:

int decValue = stoi(dec);

string hexVal;
hexVal.resize(value.length());

errno_t errCode = _itoa_s(decValue, &hexVal[0], hexVal.size() 1, 16);
if (errCode != 0)
{
    // error handling...
}
else
{
    hexVal.resize(strlen(hexVal.c_str())); // truncate any unused portion
    // use hexVal as needed...
}

CodePudding user response:

This is how I would convert to hex to string (both pre C 20 and C 20)

#include <format> // C  20
#include <string>
#include <sstream>
#include <iostream>

int main()
{
    int value = 123;

    // pre c  20 formatting
    std::ostringstream os;
    os << "0x" << std::hex << value << "n";
    std::cout << os.str();

    // c  20 formatting
    auto string = std::format("0x{:x}", value);
    std::cout << string;

    return 0;
}
  • Related